在Python中,判断字符串是否为字母、数字或全大/小写,可以使用以下内置方法:
一、判断是否为纯字母
`str.isalpha()`
```python
print(str.isalpha("HelloWorld")) True
print(str.isalpha("Hello123")) False
```
二、判断是否为纯数字
`str.isdigit()`
```python
print(str.isdigit("123456")) True
print(str.isdigit("123abc")) False
```
三、判断是否为字母数字组合
`str.isalnum()`
```python
print(str.isalnum("Hello123")) True
print(str.isalnum("Hello!123")) False
```
四、判断全大写或全小写
`str.isupper()`
```python
print(str.isupper("HELLO")) True
print(str.isupper("hello")) False
```
`str.islower()`
```python
print(str.islower("hello")) True
print(str.islower("Hello")) False
```
五、其他相关方法
`str.title()`
将字符串中每个单词的首字母大写,其余小写。例如:"this is string" → "This Is String"。
`str.capitalize()`
将字符串的第一个字符大写,其余小写。例如:"hello, world!" → "Hello, world"。
`str.isspace()`
```python
print(str.isspace(" ")) True
print(str.isspace("Hello")) False
```
示例综合应用
```python
s = "Hello123"
if s.isalpha():
print("全是字母")
elif s.isdigit():
print("全是数字")
elif s.isalnum():
print("字母和数字的组合")
elif s.isupper():
print("全大写")
elif s.islower():
print("全小写")
else:
print("包含其他字符")
```
以上方法覆盖了常见的字符串类型判断需求,可根据具体场景选择合适的方法。