字符串大小转换python
时间: 2024-01-23 17:39:55 浏览: 24
可以使用 upper() 和 lower() 方法将字符串大小写互相转换。
例如:
```python
string = "Hello World!"
new_string = string.upper() # 将字符串转换为大写
print(new_string) # 输出: HELLO WORLD!
another_string = "NICE TO MEET YOU!"
new_another_string = another_string.lower() # 将字符串转换为小写
print(new_another_string) # 输出: nice to meet you!
```
还可以使用 title() 和 capitalize() 方法将字符串的首字母变为大写。
例如:
```python
string = "hello world!"
new_string = string.title() # 将字符串的首字母变为大写
print(new_string) # 输出: Hello World!
another_string = "nice to meet you!"
new_another_string = another_string.capitalize() # 将第一个词的首字母变为大写
print(new_another_string) # 输出: Nice to meet you!
```
相关问题
python字符串大小写转换
在 Python 中,可以使用 `upper()` 方法将字符串转换为大写,使用 `lower()` 方法将字符串转换为小写,使用 `capitalize()` 方法将字符串的首字母转换为大写。
以下是示例代码:
```python
s = "Hello, World!"
# 将字符串转换为大写
print(s.upper()) # 输出: HELLO, WORLD!
# 将字符串转换为小写
print(s.lower()) # 输出: hello, world!
# 将字符串的首字母转换为大写
print(s.capitalize()) # 输出: Hello, world!
```
还可以使用 `title()` 方法将每个单词的首字母转换为大写,例如:
```python
s = "hello, world! how are you?"
# 将每个单词的首字母转换为大写
print(s.title()) # 输出: Hello, World! How Are You?
```
python输入字符串转换大小写
当我们需要将输入的字符串转换为大写或小写时,可以使用Python内置的字符串方法upper()和lower()。其中,upper()方法将字符串转换为大写,而lower()方法将字符串转换为小写。下面是一个简单的示例代码:
```
input_str = input("请输入一个字符串:")
print("转换为大写后的字符串为:", input_str.upper())
print("转换为小写后的字符串为:", input_str.lower())
```
当我们运行这段代码并输入一个字符串后,程序会将该字符串分别转换为大写和小写,并输出结果。