python学习6

Python-字符串

双引号 “ “ 表string

1
2
spam = "That is Alice's cat."
#out: That is Alice's cat.

转义字符

转义字符 打印为
```' 单引号
```" 双引号
\t 制表符
\n 换行符
``` \ 倒斜杠

e.g.

1
2
3
4
print("Hello there!\nHow are you?\nI\'m doing fine.")
#Hello there!
#How are you?
#I'm doing fine.

开头加r,表示全部为字符串

1
2
print(r'That is Carol\'s cat.')
#out:That is Carol\'s cat.

‘’’ ‘’’中加段落

1
2
3
4
5
6
7
print('''Dear Alice, 

Eve's cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,

Bob''')

out:

Dear Alice,

Eve’s cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,

Bob

“”” “””中加注释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""This is a test Python program. 

Written by Al Sweigart al@inventwithpython.com

This program was designed for Python 3, not Python 2. # annotation

"""

def spam():

"""This is a multiline comment to help

explain what the spam() function does."""

print('Hello!')

下标与切片 Subscript and slice

1
2
3
4
5
6
7
8
9
10
11
12
13
spam = 'Hello world!'
spam[0]
#out:'H'
spam[4]
#out:'o'
spam[-1]
#out:'!'
spam[0:5]
#out:'Hello'
spam[:5]
#out:'Hello'
spam[6:]
#out:'world!'
1
2
3
4
spam = 'Hello world!'
fizz = spam[0:5]
fizz
#out:'Hello'

in and not in

1
2
3
4
5
6
7
8
9
10
'Hello' in 'Hello World'
#out:True
'Hello' in 'Hello'
#out:True
'HELLO' in 'Hello World'
#out:False
'' in 'spam'
#out:True
'cats' not in 'cats and dogs'
#out:False

upper()、lower()、isupper()和 islower()

1
2
3
4
5
6
7
spam = 'Hello world!'
spam = spam.upper()
spam
#out:'HELLO WORLD!'
spam = spam.lower()
spam
#out:'hello world!'
1
2
3
4
5
6
print('How are you?') 
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')

out:

How are you?

GREat

I feel great too.

1
2
3
4
5
6
7
8
9
10
11
12
13
spam = 'Hello world!'
spam.islower()
#out:False
spam.isupper()
#out:False
'HELLO'.isupper()
#out:True
'abc12345'.islower()
#out:True
'12345'.islower()
#out:False
'12345'.isupper()
#out:False
1
2
3
4
5
6
7
8
9
10
'Hello'.upper()
#out:'HELLO'
'Hello'.upper().lower()
#out:'hello'
'Hello'.upper().lower().upper()
#out:'HELLO'
'HELLO'.lower()
#out:'hello'
'HELLO'.lower().islower()
#out:True

isX 字符串方法

  • isalpha()返回 True,如果字符串只包含字母,并且非空;

  • isalnum()返回 True,如果字符串只包含字母和数字,并且非空;

  • isdecimal()返回 True,如果字符串只包含数字字符,并且非空;

  • isspace()返回 True,如果字符串只包含空格、制表符和换行,并且非空;

  • istitle()返回 True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'hello'.isalpha()
#out:True
'hello123'.isalpha()
#out:False
'hello123'.isalnum()
#out:True
'hello'.isalnum()
#out:True
'123'.isdecimal()
#out:True
' '.isspace()
#out:True
'This Is Title Case'.istitle()
#out:True
'This Is Title Case 123'.istitle()
#out:True
'This Is not Title Case'.istitle()
#out:False
'This Is NOT Title Case Either'.istitle()
#out:False

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

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
2
3
4
5
6
7
8
9
10
11
12
'Hello world!'.startswith('Hello')
#out:True
'Hello world!'.endswith('world!')
#out:True
'abc123'.startswith('abcdef')
#out:False
'abc123'.endswith('12')
#out:False
'Hello world!'.startswith('Hello world!')
#out:True
'Hello world!'.endswith('Hello world!')
#out:True

join()和 split()

1
2
3
4
5
6
', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
1
2
'My name is Simon'.split() #默认以空格分隔
#out:['My', 'name', 'is', 'Simon']
1
2
3
4
'MyABCnameABCisABCSimon'.split('ABC')
#out:['My', 'name', 'is', 'Simon']
'My name is Simon'.split('m')
#out:['My na', 'e is Si', 'on']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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')
#out:['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']

rjust()、ljust()和 center()

1
2
3
4
5
6
7
8
'Hello'.rjust(10)
#out:' Hello'
'Hello'.rjust(20)
#out:' Hello'
'Hello World'.rjust(20)
#out:' Hello World'
'Hello'.ljust(10)
#out:'Hello '
1
2
3
4
'Hello'.rjust(20, '\*')
#out:'***************Hello'
'Hello'.ljust(20, '-')
#out:'Hello---------------'
1
2
3
4
'Hello'.center(20)
#out:' Hello '
'Hello'.center(20, '=')
#out:'=======Hello========'
1
2
3
4
5
6
7
8
def printPicnic(itemsDict, leftWidth, rightWidth): 
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))

picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)

—PICNIC ITEMS–

sandwiches.. 4

apples…… 12

cups…….. 4

cookies….. 8000

——-PICNIC ITEMS——-

sandwiches………. 4

apples………….. 12

cups……………. 4

cookies…………. 8000

strip()、rstrip()和 lstrip()删除空白字符

1
2
3
4
5
6
7
spam = ' Hello World '
spam.strip()
#out:'Hello World'
spam.lstrip()
#out:'Hello World '
spam.rstrip()
#out:' Hello World'
1
2
3
spam = 'SpamSpamBaconSpamEggsSpamSpam'
spam.strip('ampS')
#out:'BaconSpamEggs'