在Python中,字母转换可以通过以下几种方法实现:
转换为字符串
使用内置的`str()`函数可以将单个字符(字母)转换为字符串。
```python
letter = 'A'
letter_str = str(letter)
print(letter_str) 输出:'A'
print(type(letter_str)) 输出:
大小写转换
`upper()` 方法将字符串中所有字母转换为大写字母。
`lower()` 方法将字符串中所有字母转换为小写字母。
`capitalize()` 方法将字符串的首字母转换为大写字母,其余字母转换为小写字母。
`swapcase()` 方法将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。
```python
string = "hello"
new_string = string.upper()
print(new_string) 输出:'HELLO'
string = "WORLD"
new_string = string.lower()
print(new_string) 输出:'world'
string = "hello world"
new_string = string.capitalize()
print(new_string) 输出:'Hello world'
string = "Hello World"
new_string = string.swapcase()
print(new_string) 输出:'hELLO wORLD'
判断大小写
`isupper()` 方法检查字符串是否全为大写字母。
`islower()` 方法检查字符串是否全为小写字母。
`istitle()` 方法检查字符串是否每个单词的首字母都大写。
```python
string = "JUST TO TEST IT"
print(string.isupper()) 输出:False
print(string.islower()) 输出:False
print(string.istitle()) 输出:False
以上方法均会返回一个新的字符串,原始字符串不会被修改。