1. Commonly used character strings are divided into four situations:
1. A single character string, including characters, numbers, symbols, etc., such as: '1', '可', '-' and so on.
2. Pure number strings, such as: '111', '-111', '12.35', '0.456', etc.
3. Mixed strings: such as: '1AaD', 'dfge2', 'kl-):2' etc.
4. Pure letter string: such as: 'ABc', 'EFG', 'abc', etc.
2. Determine whether the string is a pure number (note that those with negative signs and decimal points are not pure numbers):
1. Use the built-in function isdigit(). Note that it cannot be used to judge the value, otherwise an error will be reported.
print('123'isdigit()) # 输出:True
print('2'isdigit()) # 输出:True
print('1.23'isdigit()) # 输出:False
print('-2'.isdigit()) #输出:False
print(1.isdigit()) #输出:SyntaxError: invalid decimal literal
2. Use the built-in function isnumeric().
print('123'.isnumeric()) #输出:True
print('2'.isnumeric()) #输出:True
print('1.23'.isnumeric()) #输出:False
print('-2'.isnumeric()) #输出:False
print(2.isnumeric()) #输出:SyntaxError: invalid decimal literal
3. Use the system number range to judge (note that the int() function does not support decimal points or negative numbers as strings)
print(-888 < int(-2.3) < 999) #输出:Ture
print(-888 < int(-2) < 999) #输出:Ture
print(-888 < int('-2') < 999) #输出:Ture
print(-888 < int('2') < 999) #输出:Ture
print(-888 < -2 < 999) #输出:Ture
print(-888 < -2.3 < 999) #输出:Ture
Note: -888 and 999 can be specified at will (the integer value range of python is unlimited).
3. Determine whether the string is a pure letter (referring to 26 letters, supporting Chinese), isalpha():
print('a123'.isalpha()) #输出:False
print('abc'.isalpha()) #输出:True
print('Abc'.isalpha()) #输出:True
print('abc3'.isalpha()) #输出:False
print('(SBc'.isalpha()) #输出:False
print('中文'.isalpha()) #输出:True
4. Determine whether the string is a mixture of numbers and letters (support Chinese), isalnum():
print('123ABc'.isalnum()) #输出:True
print('abcABc'.isalnum()) #输出:True
print('123123'.isalnum()) #输出:True
print('A1B2c3'.isalnum()) #输出:True
print('12.3'.isalnum()) #输出:False
print('-123'.isalnum()) #输出:False
print('中'.isalnum()) #输出:True
print('中文89分'.isalnum()) #输出:True
Different judgment methods can be selected according to different needs.
You can also cooperate with the string function to slice the string and make a judgment.
If you need to judge uppercase and lowercase letters, you can use functions such as islower() and isupper().