Python的字符串操作
字符串可以用单引号,也可以用双引号,但在双引号中可以在字符串中可以使用单引号。
>>>spam = "That is my'cat"
在单引号中用单引号可以在它之前加一个'\'进行转义。
原始字符串:在字符串开始的引号之前加上r,它可以忽视所有的转义字符,打印出字符串中所有的倒斜杠。
>>>print(r'That is my\'s cat.')
That is my\'s cat.
多行字符串要用三重引号,多行注释可以用"""注释内容"""
字符串下标和切片
>>>spam = 'Hello world'
>>>spam[0]
'H'
>>>spam[0:5] #不包含5,包含0,1,2,3,4
'Hello'
>>>spam[-5:-1]
'world'
>>>spam[6:]
'world!'
字符串的in 和 not in 操作符
>>>'Hello' in 'Hello world'
True
>>>'HELLO' in 'Hello world'
False
字符串方法
upper()和lower()方法返回一个新的字符串,其中原字符串的所有字母都被相应地转换为大写或小写。字符串中非字母字符保持不变。
isX 字符串方法
islower() :字符串的字母都是小写,返回True
isupper() :字符串的字母都是大写,返回True
isalpha() :字符串只包含字母,并且非空,返回True
isalnum():字符串只包含字母和数字,并且非空,返回True
isdecimal():字符串只包含数字字符,并且非空,返回True
isspace():字符串只包含空格,制表符和换行,并且非空,返回True
istitle():字符串仅包含以大写字母开头,后面都是小写字母的单词,返回True
>>>'hello'.isalpha()
True
>>>'hello123'.isalnum()
True
>>>'123'.isdecimal()
True
>>>' '.isspace() and '\n'.isspace() and '\t'.isspace()
True
>>>'This Is My Home'.istitle()
True
startswith()和endswith()方法:如果它们所调用的字符串以该方法传入的字符串开始或结束,就返回True.
>>>'Hello world'.startswith('Hello')
True
>>>'Hello world'.endswith('world')
join()方法和split()方法
>>>','.join(['cats','rats','bats'])
'cats','rats','bats'
>>>' '.join(['My','name','is','Simon'])
'My name is Simon'
>>>'My name is Simon'.split()
['My','name','is','Simon']
>>>'My name is Simon'.split('m')
['My na','e is Si','on']
rjust(),ljust()和center()方法
>>> 'Hello'.rjust(20)
' Hello'
>>> 'Hello'.rjust(20,'*')
'***************Hello'
>>> 'Hello'.ljust(10)
'Hello '
>>> 'Hello'.ljust(10,'*')
'Hello*****'
>>> 'Hello'.center(10,'*')
'**Hello***'
strip(),rstrip()和lstrip()删除空白字符>>> spam = ' Hello world '
>>> spam.strip()
'Hello world'
>>> spam.lstrip()
'Hello world '
>>> spam.rstrip()
' Hello world'