Python-字符串
双引号 “ “ 表string
1 | spam = "That is Alice's cat." |
转义字符
转义字符 | 打印为 |
---|---|
```' | 单引号 |
```" | 双引号 |
\t | 制表符 |
\n | 换行符 |
``` \ | 倒斜杠 |
e.g.
1 | print("Hello there!\nHow are you?\nI\'m doing fine.") |
开头加r,表示全部为字符串
1 | print(r'That is Carol\'s cat.') |
‘’’ ‘’’中加段落
1 | print('''Dear Alice, |
out:
Dear Alice,
Eve’s cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
“”” “””中加注释:
1 | """This is a test Python program. |
下标与切片 Subscript and slice
1 | spam = 'Hello world!' |
1 | spam = 'Hello world!' |
in and not in
1 | 'Hello' in 'Hello World' |
upper()、lower()、isupper()和 islower()
1 | spam = 'Hello world!' |
1 | print('How are you?') |
out:
How are you?
GREat
I feel great too.
1 | spam = 'Hello world!' |
1 | 'Hello'.upper() |
isX 字符串方法
isalpha()返回 True,如果字符串只包含字母,并且非空;
isalnum()返回 True,如果字符串只包含字母和数字,并且非空;
isdecimal()返回 True,如果字符串只包含数字字符,并且非空;
isspace()返回 True,如果字符串只包含空格、制表符和换行,并且非空;
istitle()返回 True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。
1 | 'hello'.isalpha() |
e.g.
1 | while True: |
Enter your age:
forty two
Please enter a number for your age.
Enter your age:
42
Select a new password (letters and numbers only):
secr3t!
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
secr3t
startswith()和 endswith()
1 | 'Hello world!'.startswith('Hello') |
join()和 split()
1 | ', '.join(['cats', 'rats', 'bats']) |
1 | 'My name is Simon'.split() #默认以空格分隔 |
1 | 'MyABCnameABCisABCSimon'.split('ABC') |
1 | spam = '''Dear Alice, |
rjust()、ljust()和 center()
1 | 'Hello'.rjust(10) |
1 | 'Hello'.rjust(20, '\*') |
1 | 'Hello'.center(20) |
1 | def printPicnic(itemsDict, leftWidth, rightWidth): |
—PICNIC ITEMS–
sandwiches.. 4
apples…… 12
cups…….. 4
cookies….. 8000
——-PICNIC ITEMS——-
sandwiches………. 4
apples………….. 12
cups……………. 4
cookies…………. 8000
strip()、rstrip()和 lstrip()删除空白字符
1 | spam = ' Hello World ' |
1 | spam = 'SpamSpamBaconSpamEggsSpamSpam' |