python中将字符变为大写_python如何同时把字符串大写变小写,小写变大写
时间: 2023-08-11 18:17:55 浏览: 116
在 Python 中,可以使用字符串的 `upper()` 方法将字符串转换为大写,使用 `lower()` 方法将字符串转换为小写。同时将字符串中的大小写进行互换,可以使用 `swapcase()` 方法。以下是示例代码:
```python
s = "Hello World"
upper_s = s.upper() # 转换为大写
lower_s = s.lower() # 转换为小写
swapcase_s = s.swapcase() # 大小写互换
print(upper_s) # 输出 "HELLO WORLD"
print(lower_s) # 输出 "hello world"
print(swapcase_s) # 输出 "hELLO wORLD"
```
需要注意的是,上述方法都是返回新的字符串,不会改变原字符串的值。如果需要改变原字符串的值,可以直接对字符串进行赋值操作。例如:
```python
s = "Hello World"
s = s.upper() # 将 s 转换为大写,并赋值给 s
print(s) # 输出 "HELLO WORLD"
```
阅读全文
相关推荐









