@zhangyu756897669
2017-08-31T15:27:47.000000Z
字数 2789
阅读 532
python官方文档
除了islower()和isupper()之外,还有几个字符串方法的名字以。这些方法返回一个描述字符串性质的布尔值。这里有一些常见的isX字符串方法:
'hello'.isalpha()
True
'hello123'.isalpha()
False
'hello123'.isalnum()
True
'hello'.isalnum()
True
'123'.isdecimal()
True
' '.isspace()
True
'This Is Title Case'.istitle()
True
'This Is Title Case 123'.istitle()
True
'This Is not Title Case'.istitle()
False
'This Is NOT Title Case Either'.istitle()
False
当您需要验证用户输入时,isX字符串方法是有帮助的。例如,以下程序反复询问用户的年龄和密码,直到它们提供有效的输入。
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')
Enter your age:
hah
Please enter a number for your age.
Enter your age:
123
Select a new password (letters and numbers only):
zhanh*
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
zhangyu
在第一个循环中,我们询问用户的年龄并将其输入存储在年龄上。如果age是一个有效的(十进制)值,我们将从第一个while循环中跳出来,并移动到第二个请求一个密码的第二个。否则,我们通知用户他们需要输入一个号码,并再次要求他们进入他们的年龄。在第二个while循环中,我们要求一个密码,将用户的输入存储在密码中,如果输入是字母数字,则会弹出循环。如果没有,我们不满意,所以我们告诉用户密码需要是字母数字,并再次要求他们输入密码。
startswith()和endswith()方法返回True,如果它们被调用的字符串值开始或结束(分别)与传递给方法的字符串;否则返回False。
'Hello world!'.startswith('Hello')
True
'Hello world!'.endswith('world!')
True
'abc123'.startswith('abcdef')
False
'abc123'.endswith('12')
False
'Hello world!'.startswith('Hello world!')
True
'Hello world!'.endswith('Hello world!')
True
这些方法是对== equals运算符的有用替代方法,只需要检查字符串的第一个或最后一个部分,而不是整个事物等于另一个字符串。
当您有一个需要连接在一起的字符串列表到单个字符串值时,join()方法很有用。在一个字符串上调用join()方法,并传递一个字符串列表,并返回一个字符串。返回的字符串是传入列表中每个字符串的连接。
', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
请注意,在连接列表参数的每个字符串之间插入字符串join()调用。例如,当在','字符串上调用join(['cats','rats','bats'])时,返回的字符串是'cats, rats, bats'。
请记住,join()在一个字符串值上被调用,并且被传递一个列表值。 (很容易意外地以其他方式调用它)。split()方法相反:它被调用一个字符串值并返回一个字符串列表。
'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
'My name is Simon'.split('m')
['My na', 'e is Si', 'on']
spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
spam.split('\n')
['Dear Alice,',
'How have you been? I am fine.',
'There is a container in the fridge',
'that is labeled "Milk Experiment".',
'',
'Please do not drink it.',
'Sincerely,',
'Bob']
传递split()参数'\ n'让我们沿着换行符分割存储在spam中的多行字符串,并返回一个列表,其中每个项目对应于字符串的一行。