[关闭]
@zhangyu756897669 2017-08-31T15:27:47.000000Z 字数 2789 阅读 532

python官方文档17.0

python官方文档


isX字符串方法

除了islower()和isupper()之外,还有几个字符串方法的名字以。这些方法返回一个描述字符串性质的布尔值。这里有一些常见的isX字符串方法:

  1. 'hello'.isalpha()

True

  1. 'hello123'.isalpha()

False

  1. 'hello123'.isalnum()

True

  1. 'hello'.isalnum()

True

  1. '123'.isdecimal()

True

  1. ' '.isspace()

True

  1. 'This Is Title Case'.istitle()

True

  1. 'This Is Title Case 123'.istitle()

True

  1. 'This Is not Title Case'.istitle()

False

  1. 'This Is NOT Title Case Either'.istitle()

False

当您需要验证用户输入时,isX字符串方法是有帮助的。例如,以下程序反复询问用户的年龄和密码,直到它们提供有效的输入。

  1. while True:
  2. print('Enter your age:')
  3. age = input()
  4. if age.isdecimal():
  5. break
  6. print('Please enter a number for your age.')
  7. while True:
  8. print('Select a new password (letters and numbers only):')
  9. password = input()
  10. if password.isalnum():
  11. break
  12. 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()String方法

startswith()和endswith()方法返回True,如果它们被调用的字符串值开始或结束(分别)与传递给方法的字符串;否则返回False。

  1. 'Hello world!'.startswith('Hello')

True

  1. 'Hello world!'.endswith('world!')

True

  1. 'abc123'.startswith('abcdef')

False

  1. 'abc123'.endswith('12')

False

  1. 'Hello world!'.startswith('Hello world!')

True

  1. 'Hello world!'.endswith('Hello world!')

True

这些方法是对== equals运算符的有用替代方法,只需要检查字符串的第一个或最后一个部分,而不是整个事物等于另一个字符串。

join()和split()String方法

当您有一个需要连接在一起的字符串列表到单个字符串值时,join()方法很有用。在一个字符串上调用join()方法,并传递一个字符串列表,并返回一个字符串。返回的字符串是传入列表中每个字符串的连接。

  1. ', '.join(['cats', 'rats', 'bats'])

'cats, rats, bats'

  1. ' '.join(['My', 'name', 'is', 'Simon'])

'My name is Simon'

  1. 'ABC'.join(['My', 'name', 'is', 'Simon'])

'MyABCnameABCisABCSimon'

  1. 'My name is Simon'.split()

['My', 'name', 'is', 'Simon']

  1. 'MyABCnameABCisABCSimon'.split('ABC')

['My', 'name', 'is', 'Simon']

  1. 'My name is Simon'.split('m')

['My na', 'e is Si', 'on']

  1. spam = '''Dear Alice,
  2. How have you been? I am fine.
  3. There is a container in the fridge
  4. that is labeled "Milk Experiment".
  5. Please do not drink it.
  6. Sincerely,
  7. Bob'''
  1. 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中的多行字符串,并返回一个列表,其中每个项目对应于字符串的一行。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注