python修改字符串大小写
时间: 2023-10-05 16:06:39 浏览: 57
Python提供了一些内置函数来修改字符串的大小写,包括:
1. upper():将字符串中所有字母转换为大写字母。
2. lower():将字符串中所有字母转换为小写字母。
3. capitalize():将字符串首字母大写,其余小写。
4. title():将字符串中每个单词的首字母大写,其余小写。
例如:
```python
string = "hello World!"
# 将字符串中所有字母转换为大写字母
string_upper = string.upper()
print(string_upper) # 输出: HELLO WORLD!
# 将字符串中所有字母转换为小写字母
string_lower = string.lower()
print(string_lower) # 输出: hello world!
# 将字符串首字母大写,其余小写
string_capitalize = string.capitalize()
print(string_capitalize) # 输出: Hello world!
# 将字符串中每个单词的首字母大写,其余小写
string_title = string.title()
print(string_title) # 输出: Hello World!
```
注意,上述函数均返回新的字符串,原字符串并未被修改。如果需要修改原字符串,可以使用赋值语句:
```python
string = "hello World!"
# 修改字符串为大写字母
string = string.upper()
print(string) # 输出: HELLO WORLD!
```