Python字符串

 

目录

创建字符串

访问字符串中的值

更新字符串

转义字符

\

\\

\'

\"

\a

\b

\e

\000

\n

\v

\t

\r

\f

\oyy

\xyy

\other

字符串运算符

+

*

[]

[ : ]

in

not in 

r/R

%

字符串格式化

%c

%s

%d

%u

%o

%x

%X

%f

%e

%E

%g

%G

格式化操作符辅助指令

*

-

+

#

0

%

(var)

m.n.

字符串方法

capitalize()

casefold()

center()

count()

decode()

encode()

endswith()

expandtabs()

find()

format

index()

isalnum()

isalpha()

isdecimal()

isdigit()

islower()

isnumeric()

isspace()

istitle()

isupper()

join()

ljust()

lower()

lstrip()

maketrans()

partition()

replace()

rfind()

rindex()

rjust()

rpartition()

rstrip()

split()

splitlines()

startswith()

strip()

swapcase()

title()

translate()

upper()

zfill()


创建字符串

使用单引号(')或者双引号(")创建字符串。Python3中,所有的字符串都是Unicode字符串。

str1 = 'Hello!'
str2 = "Hello!"
>>> print('A"B"C')
A"B"C

>>> print("A'B'C")
A'B'C

访问字符串中的值

可以使用方括号来截取字符串,同列表与元组的分片。

#           0123456789
>>> str1 = 'ABCDEFGHIJ'
#         -10987654321 
>>> str1[1]
'B'
>>> str1[:3]
'ABC'
>>> str1[8:]
'IJ'
>>> str1[-10:-7]
'ABC'
>>> str1[::2]
'ACEGI'
>>> str1[0:4:2]
'AC'
>>> str1[4:0:-1]
'EDCB'
>>> str1[-4:0:-1]
'GFEDCB'
>>> str1[-1:-4:-1]
'JIH'

更新字符串

截取字符串拼接

>>> str1 = 'these'
>>> str2 = str1[:2] + 'o' + str1[3:]
>>> str2
'those'

转义字符

\

出现在行尾时表现为续行符,表示该字符串还未结束,换行继续。出现在行中时,用于“翻译”特殊字符表示特殊含义,如下所示。

 

\\

反斜杠符号

\'

单引号

>>> 'Let\'s go!'
"Let's go!"

\"

双引号

>>> print("She said, \"Go!\"")
She said, "Go!"

\a

响铃

\b

退格(Backspace)

\e

转义

\000

\n

换行

>>> print('hello')
hello
>>> print('\nhello')

hello
>>> print('Languages:\nPython\nC\nJavaScript')
Languages:
Python
C
JavaScript

>>> a = 'Python'
>>> b = 'C'
>>> c = 'JavaScript'
>>> print('Languages:' + '\n' + a + '\n' + b + '\n' + c)
Languages:
Python
C
JavaScript

三重引号代替换行符 

>>> str = """A
B
C"""
>>> str
'A\nB\nC'
>>> print(str)
A
B
C
str1 = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (str1)

输出结果:
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB (    )。
也可以使用换行符 [
 ]。

\v

纵向制表符

\t

横向制表符

>>> print('hello')
hello
>>> print('\thello')
        hello

>>> a = 'hello'
>>> print('\t' + a)
	hello
>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
	Python
	C
	JavaScript

\r

回车

\f

换页

\oyy

八进制数,yy代表的字符,例如:\o12代表换行

\xyy

十六进制数,yy代表的字符,例如:\x0a代表换行

\other

其它的字符以普通格式输出

字符串运算符

+

字符串连接

>>> 'I love ' + 'this game!'
'I love this game!'

*

重复输出字符串

>>> 'ABC' * 3
'ABCABCABC'

[]

通过索引获取字符串中字符,见本页:《访问字符串中的值》

[ : ]

截取字符串中的一部分。见本页:《访问字符串中的值》

in

成员运算符 - 如果字符串中包含给定的字符返回 True

>>> 'D' in 'Good'
False
>>> 'd' in 'Good'
True

not in 

成员运算符 - 如果字符串中不包含给定的字符返回 True

>>> 'D' not in 'Good'
True

r/R

原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。

>>> str = 'C:\now'    #\n换行符
>>> str
'C:\now'
>>> print(str)
C:
ow

#办法1:使用原始字符串
>>> str = r'C:\now'
>>> str
'C:\\now'
>>> print(str)
C:\now

#办法:2:用反斜杠对自身进行转义
>>> str = 'C:\\now'
>>> print(str)
C:\now

注意:原始字符串不能以反斜杠结尾

>>> str = r'C:\now\'    #会报错

>>> str = r'C:\now\\'
>>> str
'C:\\now\\\\'
>>> print(str)
C:\now\\

#解决办法一:使用[:-1]
>>> str = r'C:\now\\'[:-1]
>>> str
'C:\\now\\'
>>> print(str)
C:\now\

#解决办法二:
>>> str = r'C:\now'+ '\\'
>>> str
'C:\\now\\'
>>> print(str)
C:\now\

#解决办法三:
>>> str = 'C:\\now\\'
>>> str
'C:\\now\\'
>>> print(str)
C:\now\

%

格式字符串,如下:

字符串格式化

字符串格式化的目的是:方便print时定义类型。

%c

格式化字符及其ASCII码

>>> '%c' % 97    #一项可不带括号
'a'

>>> '%c%c%c%c' % (97, 98, 99, 100)    #前后个数一致,一一对应,否则会报错
'abcd'

>>> '1%c2%c3%c4%c' % (97, 98, 99, 100)
'1a2b3c4d'

%s

格式化字符串

>>> 'I am %s. He is %s.' % ('Tom', 'Jack')
'I am Tom. He is Jack.'

%d

格式化整数

>>> 'I am %d. He is %d.' % (10, 15)
'I am 10. He is 15.'

%u

格式化无符号整型

>>> "a=%u" % 3.1415926
'a=3'

>>> "a=%u" % 0.618
'a=0'

>>> "a=%u" % 1.495000e+08
'a=149500000'

>>> "a=%u" % (-1&0xFFFFFFFF )
'a=4294967295'

%o

格式化无符号八进制数

>>> 'a=%o' % 8
'a=10'

>>> '%d转换为8进制是%o' % (10, 10)
'10转换为8进制是12'

%x

格式化无符号十六进制数

>>> 'a=%x' % 16
'a=10'

>>> '%d转换为16进制是%x' % (15, 15)
'15转换为16进制是f'

%X

作用同%x,格式化无符号十六进制数(大写)

%f

格式化浮点数字,可指定小数点后的精度

>>> 'a=%f' % 15
'a=15.000000'

>>> 'a=%f' % 3.1415926535897932
'a=3.141593'

>>> 'a=%f' % 99999999999999999999
'a=100000000000000000000.000000'

>>> 'a=%.3f' % 3.14159    #设置精度
'a=3.142'

%e

用科学计数法格式化浮点数

>>> 'a=%e' % 100
'a=1.000000e+02'

>>> 'a=%e' % 3.141592653589
'a=3.141593e+00'

>>> '光速约为%ekm/s' % 300000
'光速约为3.000000e+05km/s'

%E

作用同%e,用科学计数法格式化浮点数

%g

根据值的大小决定使用 %f 或 %e

>>> '光速约为%gkm/s,也就是%gm/s。' % (300000, 300000000)
'光速约为300000km/s,也就是3e+08m/s。

>>> '圆周率=%g' % 3.141592653589
'圆周率=3.14159'

%G

作用同%g,根据值的大小决定使用 %F 或 %E

格式化操作符辅助指令

*

定义宽度或者小数点精度

-

用做左对齐

>>> '圆周率=%6.2f' % 3.1415926
'圆周率=  3.14'    #前2个空格

>>> '圆周率=%-6.2f' % 3.1415926
'圆周率=3.14  '    #后2个空格

+

在正数前面显示加号( + )

>>> '5+5=%d' % 10
'5+5=10'
>>> '5+5=%+d' % 10
'5+5=+10'
>>> '10-20=%+d' % -10
'10-20=-10'

在正数前面显示空格

#

在八进制数前面显示零('0o'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')

>>> '%o' % 8
'10'
>>> '%#o' % 8
'0o10'


>>> '%x' % 16
'10'
>>> '%#x' % 16
'0x10'
>>> '%#X' % 16
'0X10'
>>> '%#x' % 15
'0xf'
>>> '%#X' % 15
'0XF'

0

显示的数字前面填充'0'而不是默认的空格

>>> '圆周率=%06.2f' % 3.1415926
'圆周率=003.14'

>>> '%05d' % 5
'00005'

%

'%%'输出一个单一的'%'

(var)

映射变量(字典参数)

m.n.

m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

>>> '%5d' % 5
'    5'

>>> 'a=%.3f' % 3.14159    #设置精度
'a=3.142'

>>> '圆周率=%5.1f' % 3.1415926
'圆周率=  3.1'    # 2个空格
>>> '圆周率=%5.2f' % 3.1415926
'圆周率= 3.14'    # 1个空格
>>> '圆周率=%5.3f' % 3.1415926
'圆周率=3.142'    # 0个空格
>>> '圆周率=%5.4f' % 3.1415926
'圆周率=3.1416'    # 撑大了

>>> '圆周率=%5.4e' % 3.1415926
'圆周率=3.1416e+00'

 

字符串方法

capitalize()

把字符串的第一个字符改为大写,其他字母变小写。返回一个新的字符串。

>>> temp = 'gOD IS A GIRL.'
>>> temp.capitalize()
'God is a girl.'

casefold()

把整个字符串的所有字符改为小写。

>>> temp = 'He is Tom.'
>>> temp.casefold()
'he is tom.'

center()

center(width, fillchar);返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

>>> temp = 'A'
>>> temp.center(9)
'    A    '
>>> temp.center(9,'*')
'****A****'

count()

count(sub[,start[,end]]);返回sub在字符串里出现的次数,start和end参数表示范围,可选。

>>> temp = '1abc2abc3abc4ABC'
>>> temp.count('a')
3
>>> temp.count('a', 2)    # start为索引2.
2
>>> temp.count('a', 5, 10)    # start为索引5,end为索引10
2

decode()

Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。

str = '字符串'
str_utf8 = str.encode('UTF-8')
str_gbk = str.encode('GBK')

print('UTF-8编码:', str_utf8)
print('GBK编码:', str_gbk)

print('UTF-8解码:', str_utf8.decode('UTF-8','strict'))
print('GBK 解码:', str_gbk.decode('GBK','strict'))

输出结果:
UTF-8编码: b'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2'
GBK编码: b'\xd7\xd6\xb7\xfb\xb4\xae'
UTF-8解码: 字符串
GBK 解码: 字符串

encode()

语法:str.encode(encoding='UTF-8',errors='strict')

encoding -- 要使用的编码,如: UTF-8。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能的值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

该方法返回编码后的字符串,它是一个 bytes 对象。

endswith()

endswith(sub[,start[,end]]);检查字符串是否以sub子字符串结束,是则返回True,否则返回假。start,end参数表示范围可选。

>>> #       0123456789
>>> str1 = 'Yes, I am.'
>>> str1.endswith('.')
True
>>> str1.endswith('m')
False
>>> str1.endswith('I', 0, 6)
True
>>> str1.endswith('I', 5)
False
#       0123456789
str1 = 'Yes, I am.'
str2 = 'am.'
str3 = 'es'

print(str1.endswith(str2))		# 1
print(str1.endswith(str3, 0, 3))	# 2

输出结果:
True	# 1
True	# 2

expandtabs()

expandtabs([tabsize=8]);把字符串中的的tab符号(\t)转换为空格,如不指定参数,默认的空格数tabsize=8

>>> str1 = '\t1\t1234\t1234567\t12345678\t123456789'
>>> print(str1)
	1	1234	1234567	12345678	123456789	#tab
>>> print(str1.expandtabs())
        1       1234    1234567 12345678        123456789	#空格
#   8       7        3         1            8
>>> str1 = '\t1\t1234\t12345\t123456'
>>> print(str1)
	1	1234	12345	123456	#tab
>>> print(str1.expandtabs(5))		#指定空格数
     1    1234 12345     123456		#空格
# 5    4      1       5

find()

find(sub[,start[,end]]);检测sub是否包含在字符串中,如果有则返回索引值(起始位置在字符串中的索引值),否则返回-1,start和end参数表示范围,可选。

>>> str1 = "Life is short, use Python."
>>> str1.find('is')
5
>>> str1.find('e')    #只找第1个
3
>>> str1.find('e', 4)    #设定start
17
>>> str1.find('e', 4, 17)    #设定start、end;没找到。
-1

format

按照统一的规格去输出一个字符串,接受位置参数和关键字参数(replacement,用大括号{ }表示)。

#位置参数
>>> '{0} love {1} {2}!'.format('I', 'this', 'game')
'I love this game!'
#关键字参数
>>> '{a} love {b} {c}!'.format(a = 'I', b = 'this', c = 'game')
'I love this game!'
#位置参数、关键字参数混合

>>> '{0} love {1} {c}!'.format('I', 'this', c = 'game')
'I love this game!'

>>> '{0} love {b} {c}!'.format('I', b = 'this', c = 'game')
'I love this game!'

>>> '{c} love {b} {0}!'.format('I', b = 'this', c = 'game')
'game love this I!'

>>> '{c} love {1} {0}!'.format('I', 'this', c = 'game')
'game love this I!'

注意,混合使用时位置参数必须要在关键字之前,否则会报错:

>>> '{a} love {1} {c}!'.format(a = 'I', 'this', c = 'game')
SyntaxError: positional argument follows keyword argument

替换域中冒号表示格式化符号的开始:

>>> '{0}:{1:.2f}'.format('圆周率', 3.14159)    # .2,四舍五入小数点后两位;f,浮点数
'圆周率:3.14'

关于大括号的输出:

>>> '我们把{}叫{a}。'.format('小括号', a = '大括号')
'我们把小括号叫大括号。    #与需求不符

>>> '我们把{{}}叫{a}。'.format('小括号', a = '大括号')
'我们把{}叫大括号。'    #双层大括号解决

>>> '数学中{0}是一个集合'.format('0', '1', '2')
'数学中0是一个集合'    #与需求不符

>>> '数学中{{0}}是一个集合'.format('0', '1', '2')
'数学中{0}是一个集合'    #双层大括号解决

index()

index(sub[,start[,end]]);跟find方法一样,不过如果sub不在string中会报一个异常(find方法返回-1)。

>>> str1 = 'Life is short, use Python.'
>>> str1.index('is')
5
>>> str1.index('e')    #只找第1个
3
>>> str1.index('e', 4)    #设定start
17
>>> str1.index('e', 4, 17)    #设定start、end;没找到报错。
Traceback (most recent call last):
  File "", line 1, in 
    str1.index('e', 4, 17)
ValueError: substring not found

isalnum()

如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。

>>> str1 = ''		#空字符串
>>> str1.isalnum()
False

>>> str1 = '2 plus 3'	#数字、字母、空格混合
>>> str1.isalnum()
False

>>> str1 = '2plus3'	#数字、字母混合
>>> str1.isalnum()
True

>>> str1 = '12345'	#全数字
>>> str1.isalnum()
True

>>> str1 = 'plus'	#全字母
>>> str1.isalnum()
True

isalpha()

如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。

>>> str1 = ''		#空字符串
>>> str1.isalpha()
False

>>> str1 = ‘2 plus 3’	#数字字母混合
>>> str1.isalpha()
False

>>> str1 = '12345'	#全数字
>>> str1.isalpha()
False

>>> str1 = 'plus'	#非空,全字母
>>> str1.isalpha()
True

isdecimal()

如果字符串中只包含十进制数字则返回True,否则返回False。这种方法只存在于unicode对象。

注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。

True: Unicode数字,全角数字(双字节) 
False: 罗马数字,汉字数字,小数
Error: byte数字(单字节)

>>> str = "123"
>>> str.isdecimal()
True

>>> str = "a123"
>>> str.isdecimal()
False

isdigit()

如果字符串中只包含数字则返回True,否则返回False。

True: Unicode数字,byte数字(单字节),全角数字(双字节)
False: 汉字数字,罗马数字,小数
Error: 无 

>>> str1 = "123"
>>> str1.isdigit()
True

>>> str1 = "a123"
>>> str1.isdigit()
False

islower()

如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写,则返回True,否则返回False。

>>> str1 = 'china'
>>> str1.islower()
True

>>> str1 = 'a123'
>>> str1.islower()
True

>>> str1 = 'China'
>>> str1.islower()
False

>>> str1 = 'A123'
>>> str1.islower()
False

>>> str1 = '123'
>>> str1.islower()
False

isnumeric()

如果字符串只包含数字字符,则返回True,否则返回False。这种方法是只针对unicode对象。(注:定义一个字符串为Unicode,只需要在字符串前添加 'u' 前缀即可。)

True: Unicode数字,全角数字(双字节),罗马数字,汉字数字 
False: 小数 
Error: byte数字(单字节)

>>> str1 = '123'
>>> str1.isnumeric()
True

>>> str1 = 'a123'
>>> str1.isnumeric()
False

isspace()

如果字符串中只包含空格,则返回True,否则返回False。

>>> str = ' '		#这是半角空格
>>> str.isspace()
True

>>> str = ' '		#这是全角空格
>>> str.isspace()
True

>>> str = '	'	#这是tab空格
>>> str.isspace()
True

istitle()

如果字符串是标题化(所有的单词都是以大写开始,其余字母均小写),则返回True,否则返回False。

>>> str = 'Life Is Short, Use Python.'
>>> str.istitle()
True
 
>>> str = 'china'
>>> str.istitle()
False

>>> str = 'China123'
>>> str.istitle()
True

>>> str = 'A1b2c'    #非字母字符之后的字母要大写?!
>>> str.istitle()
False

>>> str = 'A1B2C'
>>> str.istitle()
True

isupper()

如果字符串中至少包含一个区分大小写的字符,并且这些字符都是大写,则返回True,否则返回False。

>>> str = 'CHINA'
>>> str.isupper()
True

>>> str = 'China'
>>> str.isupper()
False

>>> str = 'B2B'
>>> str.isupper()
True

>>> str = 'B2b'
>>> str.isupper()
False

join()

join(sub);以字符串作为分隔符,插入到sub(可迭代对象)中的所有的字符之间,合并为一个新的字符串。

join方法在处理大量字符串拼接时比连接符号(+)效率高。另外加号连接也会引起内存复制及垃圾回收操作。

>>> '-'.join('123')
'1-2-3'

>>> ' '.join('ABC123')
'A B C 1 2 3'

>>> tup = ('a', 'e', 'i', 'o', 'u')
>>> ' '.join(tup)
'a e i o u'

>>> tup = ('a', 'e', 'i', 'o', 'u')
>>> ''.join(tup)    #用空字符join
'aeiou'

>>> list = ['a', 'e', 'i', 'o', 'u']
>>> ' '.join(list)
'a e i o u'

>>> list = ['a', 'e', 'i', 'o', 'u']
>>> ''.join(list)    #用空字符join
'aeiou'

ljust()

ljust(width[, fillchar]);返回一个原字符串左对齐,并使用 fillchar(默认为空格)填充至长度 width 的新字符串。fillchar 只能设置一个字符否则会报错。

>>> str1 = 'abc'
>>> str1.ljust(5)
'abc  '
>>> str1.ljust(5, '*')	#替换字符只能有一个
'abc**'

>>> str1 = 'abcde'
>>> str1.ljust(3, '*')	#字符串长度≥width
'abcde'

lower()

转换为字符串中所有的大写字符为小写。

>>> name = 'JACK Smith'
>>> print(name.lower())
jack smith
>>> car = 'BMW'
>>> car == 'bmw'
False
>>> car.lower() == 'bmw'
True

lstrip()

删除指定的字符(默认为字符串开头的空格)

>>> a='  Jack Smith  '    #前后有两个空格
>>> a.lstrip()
'Jack Smith  '

>>> a='****Jack Smith****'
>>> print (a.lstrip('*'))    #删除左侧指定符号
Jack Smith****
>>> a.lstrip('*')
'Jack Smith****'

maketrans()

创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。返回转换后生成的新字符串。

内建函数:
bytearray.maketrans(intab, outtab)
bytes.maketrans(intab, outtab)
str.maketrans(intab, outtab)

使用范例见本页《translate()方法》

partition()

partition(sub);找到子字符串sub,把字符擦混分成一个3元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(‘原字符串’,’ ‘,’ ‘)

>>> str = "www.abc.com"
>>> str.partition(".")
('www', '.', 'abc.com')
>>> str = "www.abc.com"
>>> str.partition("e")    #不包含e
('www.abc.com', '', '')

replace()

replace(old,new[,count]]);把字符串中的old子字符串替换成new子字符串,如果count指定,则替换不超过count次。

>>> str1 = 'I love you.'
>>> str1.replace('you', 'this game')
'I love this game.'
>>> str = 'abc-abc-abc'
>>> str.replace('a', 'A', 2)
'Abc-Abc-abc'

rfind()

rfind(sub[,start[,end]);类似于find()方法,不过是从右边开始查找。(见本页:《find()方法》,范例效果一样)

rindex()

rindex(sub[,start[,end]);类似于index()方法,不过是从右边开始查找。(见本页:《index()方法》,范例效果一样)

rjust()

rjust(width,[, fillchar]);返回一个原字符串右对齐,并使用fillchar(默认为空格)填充至长度 width 的新字符串。fillchar 只能设置一个字符否则会报错。

>>> str1 = 'abc'
>>> str1.rjust(5)
'  abc'
>>> str1.rjust(5, '*')	#替换字符只能有一个
'**abc'
>>> 
>>> str1 = 'abcde'
>>> str1.rjust(3, '*')	#字符串长度≥width
'abcde'

rpartition()

rpartition(sub);类似于partition()方法,不过是从右边开始查找。(见本页《partition()方法》)

rstrip()

语法:str.rstrip([chars]);删除指定的字符(默认为字符串末尾的空格)

>>> a='  Jack Smith  '    #前后有两个空格
>>> a.rstrip()
'  Jack Smith'

>>> a='****Jack Smith****'
>>> print (a.rstrip('*'))    ##删除右侧指定符号
****Jack Smith
>>> a.rstrip('*')
'****Jack Smith'

split()

split(sep = None,maxsplit=-1);不带参数默认是以空格为分割符切片字符串,如果maxsplit参数有设置,则仅分割maxsplit个子字符串,返回切片后的字符串拼接的列表。

>>> str = 'I love this game!'

>>> str.split()    # str.split(' ')
['I', 'love', 'this', 'game!']

>>> str.split('e', 1)    # str.split(sep='e', maxsplit=1) 亦可,这样参数也可调换位置。
['I lov', ' this game!']

>>> str.split('e', 2)    # str.split(sep='e', maxsplit=2) 或 str.split(maxsplit=2, sep='e')
['I lov', ' this gam', '!']

>>> (a, b) = str.split('o', 1)    # 拆分成a,b两段,如果maxsplit设为2会报错。
>>> a
'I l'
>>> b
've this game!'

splitlines()

splitlines(([keepends]));按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

startswith()

startswith(prefix[,start[,end]]);检测字符串是否以prefix开头,是则返回True,否则返回False,start和end参数可以指定范围检查,可选

strip()

strip([chars]);在字符串上执行 lstrip()和 rstrip(),删除字符串前边和后边所有指定字符,默认为空格。

>>> a='  Jack Smith  '    #前后有两个空格
>>> a.strip()
'Jack Smith'

>>> a='****Jack Smith****'
>>> print (a.strip('*'))    #删除前后指定字符
Jack Smith
>>> a.strip('*')
'Jack Smith'

swapcase()

翻转字符串中的大小写,大写转换为小写,小写转换为大写。

>>> str = 'Today Is My 21st Birthday.'
>>> str.swapcase()
'tODAY iS mY 21ST bIRTHDAY.'

title()

返回标题化(所有的单词都是以大写开始,其余字母均小写)的字符串。

>>> name = 'jack smith'
>>> print(name.title())
Jack Smith

 注意:非字母后的第一个字母将转换为大写字母:

>>> a = '我叫tom'
>>> b = '锤子手机t1t2涵盖3g4g5g'
>>> print(a.title())
我叫Tom
>>> print(b.title())
锤子手机T1T2涵盖3G4G5G

translate()

translate(table, deletechars="");根据table的规则(可以有str.maketrans(‘a’,’b’)定制)转换字符串中的字符, 要过滤掉的字符放到 deletechars 参数中。(参见本页:《maketrans()方法》)

语法:
str.translate(table)
bytes.translate(table[, delete])
bytearray.translate(table[, delete])

>>> intab = 'abcde'
>>> outtab = '12345'
>>> transtab = str.maketrans(intab, outtab)    #制作翻译表
>>> 
>>> str = 'abcdefedcba'
>>> str.translate(transtab)
'12345f54321'
>>> bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')# 制作翻译表
>>> print(b'runoob'.translate(bytes_tabtrans, b'o'))  # 转换为大写,并删除字母o
b'RUNB'

upper()

转换字符串中的所有小写字符为大写。

>>> name = 'jack smith'
>>> print(name.upper())
JACK SMITH

zfill()

zfill(width);返回长度为width的字符串,原字符串右对齐,前边用0填充。同:rjust(width,"0")

>>> str = 'abcde'
>>> str.zfill(8)
'000abcde'

>>> str = 'abcde'
>>> str.zfill(4)
'abcde'

 

你可能感兴趣的:(Python系统学习)