Python内置数据类型 - 文本序列类型(str)详解

文本序列类型(str)

  1. 单引号('):在单引号中允许嵌入一对双引号。
  2. 双引号("):允许嵌入一对单引号。
  3. 三引号('''):可以是三个单引号(''')的用法,也可以是三个双引号(""")的用法。三引号字符串可以跨越多行,引号内的空格也会包含在字符串中。

如果多个字符串字面值都是单个表达式的一个部分并且它们之间只有空格,那么它们将被隐式转换为单个字符串字面值。也就是说,("spam " "eggs") == "spam eggs"。

方法str.capitalize()

#使用capitalize()方法

s = 'a, B'

print(s.capitalize())

s = ' a, B'  # a 前面有空格

print(s.capitalize())

s = 'a, BCD'

print(s.capitalize())

执行后会输出:

A, b

 a, b

A, bcd

Python内置数据类型 - 文本序列类型(str)详解

方法str.casefold()

在Python语言中,str.casefold()的功能是返回字符串的小写形式,其功能和小写方法lower()相同,但casefold()的功能更强大,因为它旨在删除字符串中的所有case区别。例如,德国小写字母'ß'等效于"ss"。由于它已经是小写的,所以lower()对'ß'不起作用,而函数casefold()能够将其转换为"ss"。

s = 'ß'

print(s.lower()) #  'ß'

print('DOBI'.casefold())# 'dobi'

print('ß'.casefold())   #德语中小写字母 ß 等同于小写字母 ss, 其大写为 SS

name = 'Linux公社 www.linuxidc.com'

print(name.casefold())

执行后会输出:

Python内置数据类型 - 文本序列类型(str)详解

方法str.count()

在Python语言中,方法str.count(sub[, start[, end]])的功能是返回在[start, end]范围内的子串sub非重叠出现的次数。可选参数start和end都以切片表示法解释,分别表示字符串的开始和结束限定范围。

  1. sub:搜索的子字符串;
  2. start:字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0;
  3. end:字符串中结束搜索的位置。字符中第一个字符的索引为0。默认为字符串的最后一个位置。
str = "this is string example....wow!!!";

sub = "i";

print("str.count(sub, 4, 40) : ", str.count(sub, 4, 40))

sub = "wow";

print("str.count(sub) : ", str.count(sub))

执行后会输出:

str.count(sub, 4, 40) :  2

str.count(sub) :  1

方法str.encode()

在Python语言中,方法str.encode(encoding="utf-8", errors="strict")的功能是将字符串的编码版本作为字节对象返回,默认编码为'utf-8'。errors的默认值是'strict',意思编码错误引发一个UnicodeError。

  1. encoding:要使用的编码,如"UTF-8"。
  2. errors:设置不同错误的处理方案,默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
str = "Linux公社";

str_utf8 = str.encode("UTF-8")

str_gbk = str.encode("GBK")



print(str)



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'))

执行后会输出:

Linux公社
UTF-8 编码: b'Linux\xe5\x85\xac\xe7\xa4\xbe'
GBK 编码: b'Linux\xb9\xab\xc9\xe7'
UTF-8 解码: Linux公社
GBK 解码: Linux公社

Python内置数据类型 - 文本序列类型(str)详解

方法str.endswith()

在Python语言中,方法str.endswith(suffix[, start[, end]])的功能是如果字符串以指定的suffix结尾则返回True,否则返回False。suffix也可以是一个元组。可选的start表示从该位置开始测试,可选的end表示在该位置停止比较。

  1. suffix:该参数可以是一个字符串或者是一个元素;
  2. start:字符串中的开始位置;
  3. end:字符中结束位置。
Str='linuxidc example....wow!!!'

suffix='!!'

print (Str.endswith(suffix))

print (Str.endswith(suffix,20))

suffix='run'

print (Str.endswith(suffix))

print (Str.endswith(suffix, 0, 19))

执行后会输出:

True

True

False

False

方法str.expandtabs()

在Python语言中,方法str.expandtabs(tabsize=8)的功能是把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是8。参数“tabsize”指定转换字符串中的 tab 符号('\t')转为空格的字符数。例如下面的演示过程:

>>> '01\t012\t0123\t01234'.expandtabs()

'01      012     0123    01234'

>>> '01\t012\t0123\t01234'.expandtabs(4)

'01  012 0123    01234'
str = "this is\tstring example....wow!!!"



print ("原始字符串: " + str)

print ("替换 \\t 符号: " +  str.expandtabs())

print ("使用16个空格替换 \\t 符号: " +  str.expandtabs(16))

执行后会输出:

原始字符串: this is string example....wow!!!

替换 \t 符号: this is string example....wow!!!

使用16个空格替换 \t 符号: this is         string example....wow!!!

方法str.find()

在Python语言中,方法str.find(sub[, start[, end]])的功能是str.find(sub[, start[, end]])检测字符串中是否包含子字符串 str,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

  1. str:指定检索的字符串;
  2. beg:开始索引,默认为0;
  3. end:结束索引,默认为字符串的长度。

例如下面的演示过程。

True

str.format(*args, **kwargs)
str1 = "linuxidc example....wow!!!"

str2 = "exam";



print(str1.find(str2))

print(str1.find(str2, 5))

print(str1.find(str2, 10))

执行后会输出:

6

6

-1

方法str.format()

在Python语言中,方法str.format(*args, **kwargs)的功能是执行字符串格式化操作,调用此方法的字符串可以包含文本字面值或由花括号{}分隔的替换字段,每个替换字段包含位置参数的数字索引或关键字参数的名称。返回字符串的一个拷贝,其中每个替换字段使用对应参数的字符串值替换。例如下面的演示过程:

>>> "The sum of 1 + 2 is {0}".format(1+2)

'The sum of 1 + 2 is 3'
#format 函数可以接受不限个参数,位置可以不按顺序。

print("{} {}".format("hello", "world"))# 不设置指定位置,按默认顺序

print("{0} {1}".format("hello", "world")) # 设置指定位置

print("{1} {0} {1}".format("hello", "world"))# 设置指定位置



#也可以设置参数



print("网站名:{name}, 地址 {url}".format(name="Linux公社", url="www.linuxidc.net"))



# 通过字典设置参数

site = {"name": "菜鸟教程", "url": "www.linuxidc.net"}

print("网站名:{name}, 地址 {url}".format(**site))



# 通过列表索引设置参数

my_list = ['菜鸟教程', 'www.linuxidc.net']

print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

#也可以向 str.format() 传入对象:

class AssignValue(object):

    def __init__(self, value):

        self.value = value

my_value = AssignValue(6)

print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

执行后会输出:

hello world

hello world

world hello world

网站名:菜鸟教程, 地址 www.linuxidc.net

网站名:菜鸟教程, 地址 www.linuxidc.net

网站名:菜鸟教程, 地址 www.linuxidc.net

value 为: 6

方法str.format_map()

class Default(dict):

    def __missing__(self, key):

        return key

print('{name} was born in {country}'.format_map(Default(name='Guide')))

执行后会输出:

Guide was born in country

方法str.index()

在Python语言中,方法str.index(str, beg=0, end=len(string))的功能是检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。方法str.index()的功能与str.find()方法类似,区别在于如果index找不到要寻到的字符则会得到ValueError,而find则返回-1。

  1. str:指定检索的字符串;
  2. beg:开始索引,默认为0;
  3. end:结束索引,默认为字符串的长度。
str1 = "linuxidc example....wow!!!"

str2 = "exam";



print (str1.index(str2))

print (str1.index(str2, 5))

print (str1.index(str2, 10))

执行后会输出(未发现的会出现异常信息):

6

6

  File "zi10.py", line 6, in <module>

    print (str1.index(str2, 10))

ValueError: substring not found

方法str.isalnum()

在Python语言中,方法str.isalnum()的功能是如果字符串中的所有字符都是字母数字且至少有一个字符,则返回true,否则返回false。

str = "linuxidc2016"  # 字符串没有空格

print(str.isalnum())



str = "www.linuxidc.net"

print(str.isalnum())

执行后会输出:

True

False

方法str.isdecimal()

在Python语言中,方法str.isdecimal()的功能是如果字符串中的所有字符都是十进制字符并且至少有一个字符,则返回true,否则返回false。十进制字符是来自通用类别“Nd”的字符。此类别包括数字字符,以及可用于形成十进制数字的所有字符。要想定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。

str = "linuxidc2018"

print (str.isdecimal())



str = "23443434"

print (str.isdecimal())

执行后会输出:

False

True

方法str.isdigit()

在Python语言中,方法str.isdigit()的功能是如果字符串中的所有字符都是数字,并且至少有一个字符则返回真,否则返回假。数字包括十进制字符和需要特殊处理的数字,例如兼容性上标数字。在形式上,数字是具有属性值Numeric_Type = Digit或Numeric_Type = Decimal的字符。

str = "123456";

print (str.isdigit())



str = "linuxidc example....wow!!!"

print (str.isdigit())

执行后会输出:

True

False

方法str. isidentifier()

在Python语言中,方法str.isidentifier()的功能是检测字符串是否是字母开头,如果是则返回True。例如下面的演示过程:

'asdfghjkhl'.isidentifier()

Out[33]: True



'2asdfghjkhl'.isidentifier()

Out[34]: False

方法str.islower()

str = "linuxidc example....wow!!!"

print (str.islower())



str = "linuxidc example....wow!!!"

print (str.islower())

执行后会输出:

False

False

方法str.isnumeric()

在Python语言中,方法str.isnumeric()的功能是如果字符串中的所有字符都是数字字符,并且至少有一个字符,则返回true,否则返回false。数字字符包括数字字符和具有Unicode数字值属性的所有字符。

str = "linuxidc2016"

print (str.isnumeric())



str = "23443434"

print (str.isnumeric())

执行后会输出:

False

True

方法str.isprintable()

在Python语言中,方法str.isprintable()的功能是如果字符串中的所有字符都可打印或字符串为空,则返回true,否则返回false。不可打印字符是在Unicode字符数据库中定义为“其他”或“分隔符”的字符,除了被认为是可打印的ASCII空间(0x20)。(请注意,在此上下文中的可打印字符是在字符串上调用repr()时不应转义的字符,对处理写入sys.stdout或sys.stderr的字符串没有影响。

2.2.18  方法str.isspace()

在Python语言中,方法str.isspace()的功能是如果在字符串中只有空格字符,并且至少有一个字符,则返回True,否则返回False。空格字符是在Unicode字符数据库中定义为“其他”或“分隔符”并且具有双向属性为“WS”、“B”或“S”之一的那些字符。

str = "       "

print (str.isspace())



str = "linuxidc example....wow!!!"

print (str.isspace())

执行后会输出:

True

False

方法str.istitle()

在Python语言中,方法str.istitle()的功能是如果字符串是标题类型的字符串且至少包含一个字符,则返回 true。例如:大写字符可能只能跟着非标题类(数字、符号和转义字符)的字符和小写字符。否则返回 false。

str = "This Is String Example...Wow!!!"

print (str.istitle())



str = "This is string example....wow!!!"

print (str.istitle())

执行后会输出:

True

False

方法str.isupper()

str = "THIS IS STRING EXAMPLE....WOW!!!"

print (str.isupper())



str = "THIS is string example....wow!!!"

print (str.isupper())

执行后会输出:

True

False

方法str.join()

在Python语言中,方法str.join(iterable)的功能是以str作为分隔符,将string所有的元素合并成一个新的字符串。如果string为空,则发生TypeError错误。例如下面的演示过程。

'111'.join('asdfghjkl')

Out[55]: 'a111s111d111f111g111h111j111k111l'



'111'.join()

Traceback (most recent call last):



  File "<ipython-input-56-5fa735339586>", line 1, in <module>

    '111'.join()



TypeError: join() takes exactly one argument (0 given)
s1 = "-"

s2 = ""

seq = ("t", "o", "p", "r", "n", "e") # 字符串序列

print (s1.join( seq ))

print (s2.join( seq ))

执行后会输出:

t-o-p-r-n-e

toprne

方法str.ljust()

在Python语言中,方法str.ljust(width,fillchar)的功能是得到一个原始字符串左对齐,并使用fiichar填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原始字符串,与format的填充用法相似。

  1. width:指定长度
  2. fillchar:填充字符串,默认空格字符。
str = "linuxidc example....wow!!!"



print (str.ljust(50, '*'))

print('111'.ljust(50))

print('111'.ljust(50,'*'))

print('{0:*<50}'.format('111'))

执行后会输出:

linuxidc example....wow!!!***************************

111                                               

111***********************************************

111***********************************************

方法str.lower()

在Python语言中,方法str.lower()的功能是把所有字母转化为小写,功能与str.upper()相反。

str = "linuxidc EXAMPLE....WOW!!!"



print( str.lower() )

执行后会输出:

linuxidc example....wow!!!

方法str.lstrip()

在Python语言中,方法str.lstrip(chars)的功能是删除str左边所有出现在chars子字符串,chars为空时默认空格字符。参数“chars”用于指定截取的字符。例如下面的演示过程。

'     Wo Shi Hao ren   '.lstrip()

Out[67]: 'Wo Shi Hao ren   '



'Wo Shi Hao ren'.lstrip('fdsfsfW')

Out[68]: 'o Shi Hao ren'



'Wo Shi Hao ren'.lstrip('fdsfsfw')

Out[69]: 'Wo Shi Hao ren'
str = "     this is string example....wow!!!     ";

print( str.lstrip() );

str = "88888888this is string example....wow!!!8888888";

print( str.lstrip('8') );

执行后会输出:

this is string example....wow!!!    

this is string example....wow!!!8888888

方法str.maketrans()

在Python语言中,方法str.maketrans(x[, y[, z]])的功能是得到一个用于str.translate()的映射,其实就是一个字典。如果只有一个参数,它必须是将Unicode ordinals(整数)或字符(长度为1的字符串)映射到Unicode ordinal,字符串(任意长度)或None的字典。字符键将被转换为序数。如果有两个参数,它们必须是相等长度的字符串,并且在结果字典中,x中的每个字符将被映射到y中相同位置的字符。如果有第三个参数,它必须是一个字符串,在结果中这些字符将被映射到“None”。

intab = "aeiou"

outtab = "12345"

trantab = str.maketrans(intab, outtab)



str = "this is string example....wow!!!"

print (str.translate(trantab))

执行后会输出:

th3s 3s str3ng 2x1mpl2....w4w!!!

方法str.partition()

在Python语言中,方法str.partition(sep)的功能是在分隔符首次出现位置拆分字符串,并返回包含分隔符之前部分、分隔符本身和分隔符之后部分的3元组。如果找不到分隔符,返回包含字符串本身,跟着两个空字符串的3元组。

s1 = "I'm a good sutdent."

#以'good'为分割符,返回头、分割符、尾三部分。

s2 = s1.partition('good')

#没有找到分割符'abc',返回头、尾两个空元素的元组。

s3 = s1.partition('abc')



print(s1)

print(s2)

print(s3)

执行后会输出:

I'm a good sutdent.

("I'm a ", 'good', ' sutdent.')

("I'm a good sutdent.", '', '')

方法str.replace()

在Python语言中,方法str.replace(old,new,count)的功能是把字符串中的 old(旧字符串)替换成 new(新字符串),替换不超过count 次,count为空时不限次数。

  1. old:将被替换的子字符串;
  2. new:新字符串,用于替换old子字符串;
  3. max:可选字符串, 替换不超过max次。
str = "www.linuxidc.com.com"

print ("Linux公社主站:", str)

print ("Linux公社论坛:", str.replace("linuxidc.com.com", "linuxidc.net"))



str = "this is string example....wow!!!"

print (str.replace("is", "was", 3))

执行后会输出:

Linux公社主站: www.linuxidc.com.com

Linux公社论坛: www.linuxidc.net

thwas was string example....wow!!!

方法str.rfind()

在Python语言中,方法str.rfind(sub[, start[, end]])的功能是返回被搜索子串最后一次出现在字符串的索引位置,失败则返回-1。

  1. str:查找的字符串;
  2. beg:开始查找的位置,默认为0;
  3. end:结束查找位置,默认为字符串的长度。
str1 = "this is really a string example....wow!!!"

str2 = "is"



print (str1.rfind(str2))



print (str1.rfind(str2, 0, 10))

print (str1.rfind(str2, 10, 0))



print (str1.find(str2))

print (str1.find(str2, 0, 10))

print (str1.find(str2, 10, 0))

执行后会输出:

5

5

-1

2

2

-1

方法str.rindex()

在Python语言中,方法str.rindex(str, beg=0, end=len(string))的功能是返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常。

  1. str:查找的字符串;
  2. beg:开始查找的位置,默认为0;
  3. end:结束查找位置,默认为字符串的长度。
str1 = "this is really a string example....wow!!!"

str2 = "is"



print (str1.rindex(str2))

print (str1.rindex(str2,10))

执行后会输出:

5

Traceback (most recent call last):

  File "test.py", line 6, in <module>

    print (str1.rindex(str2,10))

ValueError: substring not found

方法str.rjust()

在Python语言中,方法str.rjust(width[, fillchar])的功能是得到一个原始字符串右对齐,并使用fiichar填充至指定长度的新字符串。若指定的长度小于原字符串的长度则返回原始字符串。与format的填充用法相似。

  1. width:指定填充指定字符后中字符串的总长度;
  2. fillchar:填充的字符,默认为空格。
str = "this is string example....wow!!!"

print (str.rjust(50, '*'))

执行后会输出:

******************this is string example....wow!!!

方法str.rpartition(char)

str = "http://www.linuxidc.com.com/"



print(str.partition("://"))

执行后会输出:

('http', '://', 'www.linuxidc.com.com/')

方法str.rsplit()

在Python语言中,方法str.rsplit(sep=None, maxsplit=-1)的功能是在字符串中,使用sep作为分隔符字符串返回一个单词列表。如果给出了maxsplit,则最多分裂为maxsplit+1个元素,从最右边开始。如果未指定sep或None任何空格的字符串是一个分隔符。

方法str.rstrip()

str = "     this is string example....wow!!!     "

print (str.rstrip())

str = "*****this is string example....wow!!!*****"

print (str.rstrip('*'))

执行后会输出:

     this is string example....wow!!!

*****this is string example....wow!!!

方法str.rstrip([chars])

在Python语言中,方法str.rstrip([chars])的功能是返回一个移去尾部字符后的字符串的拷贝。参数chars是一个字符串,指定要移除的字符集。如果省略chars参数则默认为删除空格。

str = "*****this is string example....wow!!!*****"

print (str.strip( '*' ))

执行后会输出:

this is string example....wow!!!

方法str.split()

在Python语言中,方法str.split(sep=None, maxsplit=-1)的功能是在字符串中,使用参数sep作为分隔符分割字符串,返回分割后的列表。如果给出了maxsplit参数,则至多拆分maxsplit次(因此,列表中将最多有maxsplit+1个元素)。如果没有指定maxsplit或为-1,那么分割的数量没有限制(进行所有可能的分割)。

如果给定了sep参数,连续的分隔符不分组在一起,并被视为空字符串进行分隔(例如,'1,,2'.split(',')返回['1', '', '2'])。参数sep可以由多个字符组成(例如,'1<>2<>3'.split('<>')返回['1', '2', '3'])。用指定的分隔符分隔空字符串返回['']。例如下面的演示过程:

>>>

>>> '1,2,3'.split(',')

['1', '2', '3']

>>> '1,2,3'.split(',', maxsplit=1)

['1', '2,3']

>>> '1,2,,3,'.split(',')

['1', '2', '', '3', '']

如果sep未指定或者为None,则采用一种不同的分隔算法:连续的空格被视为一个单一的分隔符,结果的开始或结尾将不包含空字符串即使该字符串有前导或尾随空白。因此,使用None分隔一个空字符串或只包含空白的字符串返回[]。例如下面的演示过程:

>>>

>>> '1 2 3'.split()

['1', '2', '3']

>>> '1 2 3'.split(maxsplit=1)

['1', '2 3']

>>> '   1   2   3   '.split()

['1', '2', '3']
str = "this is string example....wow!!!"

print (str.split( ))

print (str.split('i',1))

print (str.split('w'))

执行后会输出:

['this', 'is', 'string', 'example....wow!!!']

['th', 's is string example....wow!!!']

['this is string example....', 'o', '!!!']

方法str.splitlines()

在Python语言中,方法str.splitlines(keepends)的功能是按照行('\r', '\r\n', \n')进行分隔,得到各行元素的列表。如果keepends为 False,不包含换行符。如果为 True,则保留换行符。默认为False。参数“keepends”表示在输出结果里是否去掉换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True则保留换行符。

print('ab c\n\nde fg\rkl\r\n'.splitlines())

print('ab c\n\nde fg\rkl\r\n'.splitlines(True))

执行后会输出:

['ab c', '', 'de fg', 'kl']

['ab c\n', '\n', 'de fg\r', 'kl\r\n']

方法str.startswith()

在Python语言中,方法str.startswith(prefix[, start[, end]])的功能是如果字符串以prefix开头则返回True,否则返回False。

  1. prefix:检测的字符串,也可以是一个需要查找的前缀元组;
  2. start:可选参数用于设置字符串检测的起始位置;
  3. end:可选参数用于设置字符串检测的结束位置。
str = "this is string example....wow!!!"

print (str.startswith( 'this' ))

print (str.startswith( 'string', 8 ))

print (str.startswith( 'this', 2, 4 ))

执行后会输出:

True

True

False

方法str.strip()

在Python语言中,方法str.strip([chars])的功能是返回字符串的一个副本,删除前导和尾随字符。参数chars是一个字符串,指定要移除的字符集。如果要省略或chars参数,则默认为删除空格。参数chars不是前缀或后缀;相反,它的值的所有组合被去除,例如下面的演示过程。

>>>

>>> '   spacious   '.strip()

'spacious'

>>> 'www.example.com'.strip('cmowz.')

'example'

从字符串中剥离最外面的前导和尾随的chars参数值。从前端删除字符,直到到达未包含在chars中的字符集中的字符串字符。类似的动作发生在尾端。例如下面的演示过程:

>>>

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'

>>> comment_string.strip('.#! ')

'Section 3.2.1 Issue #32'

str.swapcase()

返回大写字符的字符串的副本转换为小写,反之亦然。请注意,s.swapcase().swapcase() == s不一定是真的。

方法str.title()

str = "this is string example from linuxidc....wow!!!"

print (str.title())

执行后会输出:

This Is String Example From linuxidc....Wow!!!

方法str.translate()

在Python语言中,方法str.translate(table[, deletechars]);的功能是返回通过给定的翻译表映射每个字符的字符串的副本,该table必须是通过__getitem__()(通常为mapping或sequence)实现索引的对象。当使用Unicode序号(整数)索引时,table对象可以执行以下任何操作:返回Unicode序号或字符串,将字符映射到一个或多个其他字符; return None,从返回字符串中删除字符;或引发LookupError异常,将字符映射到自身。

  1. table:翻译表,翻译表是通过maketrans()方法转换而来;
  2. deletechars:字符串中要过滤的字符列表。
intab = "aeiou"

outtab = "12345"

trantab = str.maketrans(intab, outtab)  # 制作翻译表



str = "this is string example....wow!!!"

print(str.translate(trantab))



#过滤掉的字符 o:

# 制作翻译表

bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')

# 转换为大写,并删除字母o

print(b'topr'.translate(bytes_tabtrans, b'o'))

执行后会输出:

th3s 3s str3ng 2x1mpl2....w4w!!!

b'TPR'

方法str.upper()

str = "this is string example from linuxidc....wow!!!";

print ("str.upper() : ", str.upper())

执行后会输出:

str.upper() :  THIS IS STRING EXAMPLE FROM linuxidc....WOW!!!

方法str.zfill()

str = "this is string example from linuxidc....wow!!!"

print ("str.zfill : ",str.zfill(40))

print ("str.zfill : ",str.zfill(50))

执行后会输出:

str.zfill :  this is string example from linuxidc....wow!!!

str.zfill :  000000this is string example from linuxidc....wow!!!

猜你喜欢

转载自www.linuxidc.com/Linux/2019-04/157902.htm