Python数据类型之字符串类型

Python字符串类型

单行字符串

单行字符串字面量由单引号(’’)或者双引号("")括起。
例如:

print('Hello, World')
print('Hello, World')

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Hello, World
Hello, World

Process finished with exit code 0

多行字符串

多行字符串字面量由三个单引号(’‘’’)或者三个双引号(""")括起。
例如:

str = """Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code."""

print(str)

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code.

Process finished with exit code 0

字符串是数组

Python中的字符串是表示**unicode字符**的字节数组。但是Python中没有字符数据类型,单个字符就是长度为1的字符串。方括号("[]")可用于访问字符串的元素。注意:字符串中第一个字符的索引为0。
例如:打印索引为1的元素。

str  = 'Hello, World'
print(str[1])

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
e

Process finished with exit code 0

例如: 通过-1索引获取字符串的最后一个元素:

str  = 'Hello, World'
print(str[-1])

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
d

Process finished with exit code 0

裁切字符串

通过裁切语法获取一个字符串的**子串**。语法是:指定开始索引结束索引,并以冒号(:)分隔开
注意:返回的子串是不包含结束索引位置的元素的。

正索引

例如:指定开始和结束索引

str  = 'Hello, World'
print(str[2:5])

输出结果:
返回从开始索引到结束索引的字符串

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
llo

Process finished with exit code 0

例如:只指定开始索引,不指定结束索引

str  = 'Hello, World'
print(str[2:])

输出结果:
返回从开始索引到字符串最后的子串

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
llo, World

Process finished with exit code 0

例如:只指定结束索引,不指定开始索引

str  = 'Hello, World'
print(str[:5])

输出结果:
返回从字符串开头到结束索引的子串

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Hello

Process finished with exit code 0

例如:即不指定开始索引,也不指定结束索引

str  = 'Hello, World'
print(str[:])

输出结果:
返回整个字符串。

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Hello, World

Process finished with exit code 0

负索引

开始索引,要比结束索引大,否则返回一个空子串。
例如:

str  = 'Hello, World'
print(str[-5:-1])

输出结果:
注意:不包含字符串的最后一个元素。如果想包含最后一个元素,则不指定最后索引-1即可

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Worl

Process finished with exit code 0

例如:

str  = 'Hello, World'
print(str[-5:])

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
World

Process finished with exit code 0

例如:开始索引大于结束索引,输出空子串

str  = 'Hello, World'
print(str[-2:-5])

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py


Process finished with exit code 0

字符串方法

获取字符串长度的len()方法

通过**len()**方法返回字符串的长度。
例如:

str  = 'Hello, World'
print(len(str))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
12

Process finished with exit code 0

删除开头和结尾空白字符的strip()方法

**strip()**语法:

  • 不带参数(或者参数为None)
    返回原字符串的副本(原字符串不会被修改),默认删除开头和结尾的空格字符。
str.strip()str.strip(None)

例如:

ss = '  spacious    '.strip()
print(ss)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
spacious

Process finished with exit code 0
  • 带参数
    返回原字符串的副本(原字符串不会被修改),移除开始和结尾处有指定的chars的字符集合。
    chars参数为指定要移除字符的字符串。
str.strip(chars)

例如:

a = 'www.example.com'
ss = a.strip('cmowz.')
print(ss)
print(a)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
example
www.example.com

Process finished with exit code 0

只删除开头的前导符的lstrip()方法

返回原字符串的副本,移除其中的前导字符。 chars 参数为指定要移除字符的字符串。 如果省略或为 None,则 chars 参数默认移除空格符。 实际上 chars 参数并非指定单个前缀;而是会移除参数值的所有组合。
**lstrip()**方法的语法:

str.lstrip()

例如:

a = '==========spacious=========='.lstrip('=')
print(a)
a= 'www.example.com'.lstrip('cmowz.')
print(a)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
spacious==========
example.com

Process finished with exit code 0

只删除结尾字符符的rstrip()方法

**rstrip()**方法的语法:
返回原字符串的副本,将所有大写字符转换为小写字符。

str.rstrip([chars])

例如:

将大写字符转换为小写字符的lower()方法

**lower()**方法的语法:
返回原字符串的副本,将所有大写字符转换为小写字符。

str.lower()

例如:

a = 'WWW.Example.Com'
ss = a.lower()
print(ss)
print(a)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
www.example.com
WWW.Example.Com

Process finished with exit code 0

将小写字符转换为大写字符的upper()方法

**upper()**方法的语法:
返回原字符串的副本,将所有小写字符转换为大写字符。

str.upper()

例如:

a = 'www.example.com'
ss = a.upper()
print(ss)
print(a)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
WWW.EXAMPLE.COM
www.example.com

Process finished with exit code 0

替换字符串的replace()方法

**replace()**方法的语法:

str.replace(oldStr, newStr [,count])

返回原字符串的副本,将所有子串为**oldStr的字符串替换为newStr字符串。第三个参数count是可选的,如果省略则替换所有的oldStr子串;如果指定则将前countoldStr替换为newStr**。
例如:

a = 'www.example.com'
ss = a.replace('example', 'mycompany')
print(ss)
print(a)
b = 'apple, orange, apple, banana, pen, apple'
# 默认替换所有oldStr
str1 = b.replace('apple', 'pencile')
# 只替换前2次的oldStr
str2 = b.replace('apple', 'computer', 2)
print(b)
print(str1)
print(str2)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
www.mycompany.com
www.example.com
apple, orange, apple, banana, pen, apple
pencile, orange, pencile, banana, pen, pencile
computer, orange, computer, banana, pen, apple

Process finished with exit code 0

拆分字符串的split()方法

**split()**方法的语法:

str.split(sep=None, maxsplit=-1)

返回一个(由字符串内)单词(组成的)列表,使用sep分割字符串。

  • maxsplit参数
    maxsplit参数指定了最大的拆分次数(因此,列表中最多会有maxsplit+1个元素)。
    例如:
li = '1,2,3'.split(',', maxsplit=1)
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['1', '2,3']

Process finished with exit code 0

如果maxsplit未指定或者为-1,则不限制拆分次数。
例如:

li = '1,2,3'.split(',')
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['1', '2', '3']

Process finished with exit code 0
  • sep参数
    如果指定了sep,则连续的分隔符不会被组合在一起而是被视为分隔空字符串。
    例如:
li = '1,2,,3,'.split(',')
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['1', '2', '', '3', '']

Process finished with exit code 0

sep 参数可能由多个字符组成。
例如:

li =  '1<>2<>3'.split('<>')
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['1', '2', '3']

Process finished with exit code 0

使用指定的分隔符拆分空字符串将返回 [’’]。
例如:

li =  ''.split(',')
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['']

Process finished with exit code 0

如果未指定sep或者为None, 默认以空格作为分隔符(连续的空格被视为单个空格).
例如:

li =  '1 2 3'.split()
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['1', '2', '3']

Process finished with exit code 0

如果字符串包含前缀或后缀空格,其结果将不包含开头或末尾的空字符串。
例如:

li =  '   1   2   3   '.split()
print(li)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['1', '2', '3']

Process finished with exit code 0

因此,使用 None 拆分空字符串或仅包含空格的字符串将返回 [].
例如:

li =  ''.split(None)
print(li)
lli = '          '.split(None)
print(lli)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
[]
[]

Process finished with exit code 0

拆分字符串的rsplit()方法

**rsplit()**方法的语法:
返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。 如果给出了 maxsplit,则最多进行 maxsplit 次拆分,从 最右边 开始。 如果 sep 未指定或为 None,任何空白字符串都会被作为分隔符

str.rsplit(sep=None, maxsplit=-1)

拆分多行字符串的splitlines()方法

返回由原字符串中各行组成的列表,在行边界的位置拆分。 结果列表中不包含行边界,除非给出了 keepends == True则包含行边界如\n。
**splitlines()**方法的语法:

str.splitlines([keepends])

行边界包括:

行边界符 描述
\n 换行符
\r 回车符
\r\n 回车 + 换行
\v或\x0b 行制表符
\f或\x0c 换表单
\xlc 文件分隔符
\xld 组分隔符
\xle 记录分隔符
\x85 下一行
\u2028 行分隔符
\u2029 段分隔符

例如:

a = '''124
abcd
789
abced123
'''
print(a.splitlines())
print(a.splitlines(True))
a = 'abce\n\n7890\nabcde\n\ruuuuu'
print(a.splitlines())
print(a.splitlines(True))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
['124', 'abcd', '789', 'abced123']
['124\n', 'abcd\n', '789\n', 'abced123\n']
['abce', '', '7890', 'abcde', '', 'uuuuu']
['abce\n', '\n', '7890\n', 'abcde\n', '\r', 'uuuuu']

Process finished with exit code 0

将字符串首字符大写,其余字符都小写的capitalize()方法

语法:

str.capitalize()

返回原字符串的副本,其首个字符大写,其余为小写,例如:

s = 'hello,WORLD'
print(s.capitalize())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Hello,world

Process finished with exit code 0

消除字符串大小写的casefold()方法

语法:

str.casefold()

返回原字符串消除大小写的副本。
消除大小写类似于转为小写,但是更加彻底一些,因为它会移除字符串中的所有大小写变化形式。例如,德语小写字母 ‘ß’ 相当于 “ss”。 由于它已经是小写了,lower() 不会对 ‘ß’ 做任何改变;而 casefold() 则会将其转换为 “ss”。
例如:

s = 'hello,WORLD'
print(s.casefold())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
hello,world

Process finished with exit code 0

将指定长度的字符串放在填充字符的中间的center()方法

语法:

str.center(width[, fillchar])

返回长度为 width 的字符串,原字符串在其正中。使用指定的 fillchar 填充两边的空位(默认使用 ASCII 空格符)。 如果 width 小于等于 len(s) 则返回原字符串的副本。例如:

s = 'hello,WORLD'
print(s.center(50, '*'))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
*******************hello,WORLD********************

Process finished with exit code 0

返回字符串出现次数的count()方法

语法:

str.count(sub[, start[, end]])

反回子字符串 sub 在 [start, end] 范围内非重叠出现的次数。 可选参数 start 与 end 会被解读为切片表示法。

  • 不指定范围start和end
  • 只指定范围的start
  • 同时指定start和end
    例如:
s = 'hello,sir, the world is well, hello, world,hello,everyone, hello, world'
print(s.count('hello'))
print(s.count('hello, world'))

print(s.count('hello, world', 10))
print(s.count('hello, world', 10, 50))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
4
2
2
1

Process finished with exit code 0

设置字符串编码方式的encode()方法

语法:

str.encode(encoding="utf-8", errors="strict")

返回原字符串编码为字节串对象的版本。 默认编码为 ‘utf-8’。可以给出 errors 来设置不同的错误处理方案。errors 的默认值为 ‘strict’,表示编码错误会引发 UnicodeError。其他可用的值为 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及任何其他通过 codecs.register_error() 注册的值错误处理方案

检查字符串是否以指定的字符串开始的startswith()方法。

语法:

str.startswith(prefix[, start[, end]])

如果字符串以指定的 prefix 开始则返回 True,否则返回 False。 prefix 也可以为由多个供查找的前缀构成的元组。 如果有可选项 start,将从所指定位置开始检查。 如果有可选项 end,将在所指定位置停止比较。

检查字符串是否以指定的字符串结尾的endswith()方法。

语法:

str.endswith(suffix[, start[, end]])

如果字符串以指定的 suffix 结束返回 True,否则返回 False。
suffix 也可是单个字符串,例如:

s = 'hello,sir, the world is well, hello, world,hello,everyone, hello, world'
print(s.endswith('world'))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True

Process finished with exit code 0

suffix也可是多个字符串组成的元组,例如:

s = 'hello,sir, the world is well, hello, world,hello,everyone, hello, world'
print(s.endswith(('world','hello', 'd', 'well'),0))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True

Process finished with exit code 0

如果有可选项 start,将从所指定位置开始检查。 如果有可选项 end,将在所指定位置停止比较。

展开制表符/t的expandtabs()方法。

语法:

str.expandtabs(tabsize=8)

将字符串中的所有制表符/t全部替换成一个或者多个空格,并返回替换后的字符串副本。参数tabsize表示每tabsize个字符设置一个制表位(默认是8个字符设置一个制表位,即在第0列,8列,16列…设置制表位)。(输出终端的)最左边为第0列。
要展开字符串,当前列将被设为零并逐一检查字符串中的每个字符。 如果字符为制表符 (\t),则会在结果中插入一个或多个空格符,直到当前列等于下一个制表位。(制表符本身不会被复制。)如果字符为换行符 (\n) 或回车符 (\r),它会被复制并将当前列重设为零。任何其他字符会被不加修改地复制并将当前列加一,不论该字符在被打印时会如何显示。
例如:

s = '01\t012\t0123\t01234'
print(s.expandtabs())
print(s.expandtabs(4))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
01      012     0123    01234
01  012 0123    01234

Process finished with exit code 0

注意:默认tabsize为8时, 在01和012之间有6个空格, 第一个制表位从第0列开始,也就是在01的0位置,第二个制表位从012的0开始,因此在012和0123之间有5个空格,第三个制表位从0123上的0开始,因此0123和01234之间有4个空格

返回找到的第一个子字符串索引的find()方法。

语法:

str.find(sub[, start[, end]])

返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。
可选参数 start 与 end 会被解读为切片表示法。 如果 sub 未被找到则返回 -1。
例如:

a = 'hello, world'
print(a.find('wor'));
print(a.find('wor', 3));
print(a.find('wor', 3, 5));
print(a.find('wor', -5, -1));

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
7
7
-1
7

Process finished with exit code 0

返回找到一个字符串中子字符串的最大索引的rfind()方法。

语法:

str.rfind(sub[, start[, end]])

返回找到的第一个子字符串索引的index()方法。

语法:

str.index(sub[, start[, end]])

类似于find()方法,当找不到时引发ValueError异常。
例如:

a = 'hello, world, hello, world'
print(a.index('wor'));
print(a.index('wor', -5, -1));
print(a.index('wor', 3));
print(a.index('wor', 3, 5));

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
7
21
7
Traceback (most recent call last):
  File "E:/Python3/Exercise/venv/05.py", line 146, in <module>
    print(a.index('wor', 3, 5));
ValueError: substring not found

Process finished with exit code 1

返回找到的一个字符串中的子字符串的最大索引的rindex()方法。

语法:

str.index(sub[, start[, end]])

判断一个字符串中的所有字符是否是字母或数字的isalnum()方法。

语法:

str.isalnum()

例如:

a = 'hello, world, hello, world'
print(a.isalnum())
a = 'helloworldhelloworld'
print(a.isalnum())
a = 'helloworldhe678lloworld'
print(a.isalnum())

a = '123456'
print(a.isalnum())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
False
True
True
True

Process finished with exit code 0

判断一个字符串中的所有字符是否都是字母的isalpha()方法。

语法:

str.isalpha()

例如:

a = 'hello, world, hello, world'
print(a.isalpha())
a = 'helloworldhelloworld'
print(a.isalpha())
a = 'helloworldhe678lloworld'
print(a.isalpha())

a = '123456'
print(a.isalpha())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
False
True
False
False

Process finished with exit code 0

判断一个字符串中的所有字符是否都是ASCII码的isascii()方法。

语法:

str.isascii()

例如:

a = 'hello, world, hello, world'
print(a.isascii())
a = 'helloworldhelloworld#$%^&*'
print(a.isascii())
a = 'helloworldhe678lloworld'
print(a.isascii())

a = '123456'
print(a.isascii())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
True
True
True

Process finished with exit code 0

判断一个字符串中的所有字符是否都是十进制字符的isdecimal()方法。

语法:

str.isdecimal()

例如:

a = '123456'
print(a.isdecimal())
a = '0x123'
print(a.isdecimal())
a = '0b1234'
print(a.isdecimal())
a = '123abce'
print(a.isdecimal())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
False
False
False

Process finished with exit code 0

判断一个字符串中的所有字符是否都是数字的isdigit()方法。

语法:

str.isdigit()

例如:

a = '123456'
print(a.isdigit())
a = '0x123'
print(a.isdigit())
a = '0b1234'
print(a.isdigit())
a = '123abce'
print(a.isdigit())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
False
False
False

Process finished with exit code 0

判断一个字符串是否是有效标识符的isidentifier()方法。

有效的标识符指的的有效的单词或者关键字。
语法:

str.isidentifier()

例如:

from keyword import iskeyword

a, b = 'hello'.isidentifier(), iskeyword('hello')
print(a, b)

a, b = 'def'.isidentifier(), iskeyword('def')
print(a, b)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True False
True True

Process finished with exit code 0

判断一个字符串中的所有字母是否都是小写的islower()方法。

语法:

str.islower()

例如:

a = '123144abceef'
print(a.islower())
a = '123144Abceef'
print(a.islower())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
False

Process finished with exit code 0

判断一个字符串中的所有字符是否都是数字的isnumberic()方法。

语法:

str.isnumeric()

例如:

a = '123144abceef'
print(a.isnumeric())
a = '123144Abceef'
print(a.isnumeric())

a = '123144'
print(a.isnumeric())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
False
False
True

Process finished with exit code 0

判断一个字符串中的所有字符是否都是可打印的的isprintable()方法。

语法:

str.isprintable()

例如:

a = '      '
print(a.isprintable())
a = '\t\t\r\n'
print(a.isprintable())
a = '123144'
print(a.isprintable())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
False
True

Process finished with exit code 0

判断一个字符串中的所有字符是否都是空白字符的isspace()方法。

语法:

str.isspace()

例如:

a = '      '
print(a.isspace())
a = '\t\t\r\n'
print(a.isspace())
a = '123144'
print(a.isspace())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
True
False

Process finished with exit code 0

返回一个字符串的标题版本字符串的title()方法。

返回原字符串的标题版本,其中每个单词第一个字母为大写,其余字母为小写。
语法:

str.title()

例如:

a = 'Hello world'.title()
print(a)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Hello World

Process finished with exit code 0

判断一个字符串是否是标题字符串的istitle()方法。

标题字符串是第一个字符为字母且是大写随后的字母必须都是小写
语法:

str.istitle()

例如:

a = 'Hello'
print(a.istitle())
a = 'HelloWorld'
print(a.istitle())
a = 'HEllo'
print(a.istitle())
a = 'Hello3'
print(a.istitle())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
False
False
True

Process finished with exit code 0

判断一个字符串中的所有字母是否都是大写的isupper()方法。

语法:

str.isupper()

例如:

a = '123144abceef'
print(a.isupper())
a = '123144Abceef'
print(a.isupper())
a = '123144ABCED'
print(a.isupper())

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
False
False
True

Process finished with exit code 0

迭代拼接指定的字符串的join()方法。

拼接的次数取决于str中的字符个数,str字符串中的字符将作为拼接字符串的间隔字符。
语法:

str.join(iterable)

例如:

a = 'abce'
b = '3214'
c = a.join(b)
print(c)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
3abce2abce1abce4

Process finished with exit code 0

返回一个指定长度字符串的ljust()方法。

源字符串在最左边,填充的字符串在右边,如果 width 小于等于 len(s) 则返回原字符串的副本
语法:

str.join(iterable)

例如:

a = 'hello, python'
print(a.ljust(3, '*'))

a = 'hello, python'
print(a.ljust(30, '*'))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
hello, python
hello, python*****************

Process finished with exit code 0

返回一个指定长度字符串的rjust()方法。

源字符串在最右边边,填充的字符串在左边边,如果 width 小于等于 len(s) 则返回原字符串的副本
语法:

str.rjust(width[, fillchar])

按指定的间隔符拆分字符串的partition()方法。

在 sep 首次出现的位置拆分字符串,返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身,以及分隔符之后的部分。 如果分隔符未找到,则返回的 3 元组中包含字符本身以及两个空字符串。
语法:

str.partition(sep)

例如:

a = 'abcedfg,123456,rgtyu,'.partition(',')
print(a)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
('abcedfg', ',', '123456,rgtyu,')

Process finished with exit code 0

按指定的间隔符拆分字符串的rpartition()方法。

在 sep 最后出现的位置拆分字符串,返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身,以及分隔符之后的部分。 如果分隔符未找到,则返回的 3 元组中包含字符本身以及两个空字符串。
语法:

str.rpartition(sep)

将一个字符串中的大写字符转化为小写,小写转换为大写字符的swapcase()方法。

语法:

str.swapcase()

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

将字符串长度填充为指定长度的zfill()方法。

语法:

str.zfill(width)

返回原字符串的副本,在左边填充 ASCII ‘0’ 数码使其长度变为 width。 正负值前缀 (’+’/’-’) 的处理方式是在正负符号 之后 填充而非在之前。 如果 width 小于等于 len(s) 则返回原字符串的副本。
例如:

a= "42".zfill(5)
print(a)
b = "-42".zfill(5)
print(b)

例如:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
00042
-0042

Process finished with exit code 0

字符串检查关键字in和not in

使用关键字innot in检查特定短语或者字符是否存在某个字符中。

text = 'China is a greate country'
ret = 'hin' in text
print(ret)
res = 'hello' not in text
print(res)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
True
True

Process finished with exit code 0

字符串拼接运算符"+"

可以使用"+"运算符,将两个字符串拼接成一个字符串。
例如:

a = 'Hello'
b = 'World'
c = a + ', ' + b
print(c)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Hello, World

Process finished with exit code 0

字符串格式化

format()方法的字符串格式

format()语法:

str.format(*args, **kwargs)

返回一个字符串格式化后的副本。花括号"{}"作为占位符。占位符的格式为:

{
    
    [field_name] [!conversion] [:format_spec]}

可选的field_name

field_name是format()方法中的位置参数数字索引

例如:

str = '{0}, {1}, {2}'.format('a', 'b', 'c')
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
a, b, c

Process finished with exit code 0

"{0}"中的0表示的是format(‘a’, ‘b’, ‘c’)方法中参数‘a’的位置索引。
"{1}"中的1表示的是format(‘a’, ‘b’, ‘c’)方法中参数‘b’的位置索引。
"{2}"中的2表示的是format(‘a’, ‘b’, ‘c’)方法中参数‘c’的位置索引。

省略占位符“{}”中的位置参数

如果格式化字符串中的占位符{}中的位置索引是和format()方法中的参数是连续对应的,则可以将{}中的位置索引省略,例如:

str = '{}, {}, {}'.format('a', 'b', 'c')
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
a, b, c

Process finished with exit code 0
格式化字符串中任意顺序引用位置参数

在格式化字符串中按任意顺序引用format()中的参数,例如

str = '{2}, {0}, {1}'.format('a', 'b', 'c')
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
c, a, b

Process finished with exit code 0
格式化字符串中重复引用位置参数

在格式化字符串中重复引用format()方法中的参数,例如:

str = '{2}, {1}, {1}, {0}'.format('a', 'b', 'c')
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
c, b, b, a

Process finished with exit code 0
格式化字符串中引用解包序列

在格式化字符串中引用format()的解包的参数序列,例如

str = '{3}, {2}, {1}, {0}'.format(*'abcd')
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
d, c, b, a

Process finished with exit code 0

field_name是format()方法中的命名参数

格式化字符串中引用参数名

例如:

str = 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Coordinates: 37.24N, -115.81W

Process finished with exit code 0
格式化字符串中引用字典的键名

例如:

coord = {
    
    'latitude': '37.24N', 'longitude': '-115.81W'}
str = 'Coordinates: {latitude}, {longitude}'.format(**coord)
print(str)

注意: 一个星号表示解引用列表,两个星号用于解引用字典
输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Coordinates: 37.24N, -115.81W

Process finished with exit code 0

field_name是format()方法中的参数的属性

  • 例如访问一个复数的属性
c = 3-5j
str = 'The complex number {0} is formed from the real part {0.real} and the imaginary part {0.imag}.'.format(c)
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.

Process finished with exit code 0
  • 例如访问一个类的属性
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __str__(self):
        return 'Point({self.x}, {self.y})'.format(self=self)
p = Point(4, 2)
print(p)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Point(4, 2)

Process finished with exit code 0

field_name是format()方法中的参数的项

  • 例如,访问一个元组中的元素
t = ('a','b','c')
str = '0: {0[0]}, 1: {0[1]}, 2: {0[2]}'.format(t)
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
0: a, 1: b, 2: c

Process finished with exit code 0

可选的!conversion

在对字符串格式化之前,对format()方法中的参数进行强制类型转换。目前支持三种类型转换:

  1. !s
    会对引用的format()中的参数调用str()方法,如果使用!s转换一个字符串,则在格式化输出中不会带引号,例如:
str =  "str() doesn't: {!s}".format('test1')
print(str)

输出结果:

在这里插入代码片
  1. !r
    会对引用的format()中的参数调用repr()方法,如果使用!r转换一个字符串,则在格式化输出中会带引号,例如:
str =  "repr() shows quotes: {!r}".format('test1')
print(str)

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
str() doesn’t: test1

Process finished with exit code 0

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
repr() shows quotes: 'test1'

Process finished with exit code 0
  1. !a
    会对引用的format()中的参数调用ascii()方法

可选的:format_spce

可选的格式说明符的语法:

[[fill]align] [sign] [#] [0] [width] [grouping_option] [.precision] [type]

可选的填充字符以及对齐方式

fill指的是可选的任意字符。只有指定了align对齐方式才可以选择是否指定填充字符,如果不指定,默认的填充字符是空格。一般和宽度[width]结合使用
可选的对齐方式有:

  1. <
    强制字段在可用空间内按左进行对齐(大多数对象的默认对齐方式)。
    例如:
s1='{:<30} ******'.format('left align')
print(s1)
s2='{:30} ******'.format('left align')
print(s2)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
left align                     ******
left align                     ******

Process finished with exit code 0
  1. >
    强制字段在可用空间内右对齐(这是数字的默认值)。
    例如:
s1='{:>30} ******'.format('left align')
print(s1)
s2='{:30} ******'.format('left align')
print(s2)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
                    left align ******
left align                     ******

Process finished with exit code 0
  1. ^
    强制字段在可用空间内居中。
    例如:
s1='{:^30} ******'.format('left align')
print(s1)
s2='{:30} ******'.format('left align')
print(s2)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
          left align           ******
left align                     ******

Process finished with exit code 0
  1. =
    强制将填充放置在符号(如果有)之后但在数字之前。此对齐选项仅对数字类型有效。当’0’紧接在字段宽度之前时,‘0’将作为默认填充字符,如果不在宽度[width]之前指定’0’,也可以在[fill]字段指定’0’,效果一样。

指定符号

s = '{:=+08}'.format(12)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
+0000012

Process finished with exit code 0

不指定符号

s = '{:=08}'.format(12)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
00000012

Process finished with exit code 0

注意: 如果不显示指定字段的宽度,即使使用对齐方式也没有任何效果,例如

s1 = '{:>} ******'.format(12)
print(s1)
s2 = '{:>30} ******'.format(12)
print(s2)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
12 ******
                            12 ******

Process finished with exit code 0

可选符号

符号sign仅仅对数字类型有效。

可选符号‘+’

该符号只应用于正数和负数。
例如,应用于正数

s1 = '****** {:=+04} ******'.format(12)
print(s1)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
****** +012 ******

Process finished with exit code 0

例如,应用于负数

s1 = '****** {:=+04} ******'.format(-12)
print(s1)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
****** -012 ******

Process finished with exit code 0
可选符号’-’

该符号只应用于负数,如果不指定sign,默认就是该符号。
例如: 如果是正数则在输出时不显示sign,如果是负数默认会显示sign

s1 = '****** {:=04} ******'.format(-12)
print(s1)
s2 = '****** {:=-04} ******'.format(-12)
print(s2)
s3 = '****** {:=-04} ******'.format(12)
print(s3)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
****** -012 ******
****** -012 ******
****** 0012 ******

Process finished with exit code 0
可选符号空格

表示应在正数上使用前导空格,在负数上使用减号。
例如:

s1 = '****** {:= 04} ******'.format(12)
print(s1)
s2 = '****** {:= 04} ******'.format(-12)
print(s2)
s3 = '****** {:=04} ******'.format(12)
print(s3)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
******  012 ******
****** -012 ******
****** 0012 ******

Process finished with exit code 0

可选的‘#’

选项仅对整数、浮点、复数和 Decimal 类型有效。

  • 对于整数类型:
    当使用二进制、八进制或十六进制输出时,此选项会为输出值添加相应的 ‘0b’, ‘0o’ 或 ‘0x’ 前缀。
    例如:
s = 'b: {:#b}'.format(100)
print(s)
s = 'd: {:#d}'.format(100)
print(s)
s = 'o: {:#o}'.format(100)
print(s)
s = 'x: {:#x}'.format(100)
print(s)
s = 'X: {:#X}'.format(100)
print(s)
s = 'n: {:#3}'.format(100)     # 指定输出的宽度为3(100正好是3个宽度,不需要添加前导空格)
print(s)
s = 'n: {:#6}'.format(100)     # 指定输出的宽度为6(需要添加3个前导空格)
print(s)
s = 'None: {:#}'.format(100)   # 默认以10进制显示
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
b: 0b1100100
d: 100
o: 0o144
x: 0x64
X: 0X64
n: 100
n:    100
None: 100

Process finished with exit code 0
  • 对于浮点数、复数和 Decimal 类型:
    转换的结果总是带小数部分。
    例如:
s = 'e: {:#e}'.format(100)  #指数形式, 6个小数精度
print(s)
s = 'E: {:#E}'.format(100)
print(s)
s = 'f: {:#f}'.format(100)  # 6个小数精度
print(s)
s = 'F: {:#F}'.format(100)
print(s)
s = 'g: {:#g}'.format(100)  # 3个小数精度
print(s)
s = 'G: {:#G}'.format(100)
print(s)
s = '%: {:#%}'.format(1.0)  # 对数字 x100并带6个小数精度
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
e: 1.000000e+02
E: 1.000000E+02
f: 100.000000
F: 100.000000
g: 100.000
G: 100.000
%: 100.000000%

Process finished with exit code 0

可选的grouping_option

可选的‘,’

表示使用’,'作为数字的千位分隔符。
例如:

a = 1234567890
s = '{:,}'.format(a)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1,234,567,890

Process finished with exit code 0
可选的‘_’
  • 表示对浮点数和整数表示类型为’d’的,使用下划线作为千位分隔符。
    例如:
a = 1234567890.456788
s = '{:_}'.format(a)
print(s)
b = 5678903245
s = '{:_}'.format(b)
print(s)
s = '{:_d}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1_234_567_890.456788
5_678_903_245
5_678_903_245

Process finished with exit code 0
  • 对于整数表示类型为’b’, ‘o’,‘x’和’X’的,将为每4个数位插入一个下划线。
b = 5678903245
s = '{:_b}'.format(b)
print(s)
s = '{:_o}'.format(b)
print(s)
s = '{:_x}'.format(b)
print(s)
s = '{:_X}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1_0101_0010_0111_1101_0010_1111_1100_1101
522_3722_7715
1_527d_2fcd
1_527D_2FCD

Process finished with exit code 0

可选的字段宽度width

width 是一个定义最小总字段宽度的十进制整数,宽度包括: 任何前缀分隔符其他格式化字符
如果未指定,则字段宽度将由内容确定。

  • 如果指定的宽度小于等于内容的宽度,则按内容实际的宽度输出,例如:
b = 5678903245
s = '{:03}'.format(b)
print(s)

输出结果:

b = 5678903245
s = '{:03}'.format(b)
print(s)
  • 如果指定的宽度大于内容宽度,可以指定填充字符,例如:
b = 5678903245
s = '{:015}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
000005678903245

Process finished with exit code 0

可选的.precision

precision 是一个十进制数字, 表示对于以 ‘f’ and ‘F’ 格式化的浮点数值要在小数点后显示多少个数位,例如:

b = 12345.0
s = '{:.3f}'.format(b)
print(s)
s = '{:.3F}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
12345.000
12345.000

Process finished with exit code 0

或者对于以 ‘g’ 或 ‘G’ 格式化的浮点数值要在小数点前后共显示多少个数位(即整数部分和小数部分之和)。例如:

b = 12345.0
s = '{:.4g}'.format(b)
print(s)
s = '{:.4G}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1.234e+04
1.234E+04

Process finished with exit code 0

可选的表示类型type

字符串表示类型
类型字符 含义
s 字符串格式。对于字符串,是默认类型,可以省略
None 同s

例如:

b = '123456'
s = '{:s}'.format(b)
print(s)
s = '{}'.format(b)
print(s)
print(type(s))

输出结果

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
123456
123456
<class 'str'>

Process finished with exit code 0
整数表示类型
类型字符 含义
b 二进制格式。输出以 2 为基数的数字

例如:

b = 65
s = '{:b}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1000001

Process finished with exit code 0
类型字符 含义
c 字符, 在打印之前将整数转换为相应的unicode字符

例如:

b = 65
s = '{:c}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
A

Process finished with exit code 0
类型字符 含义
d 十进制整数。 输出以 10 为基数的数字。

例如:

b = 65
s = '{:d}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
65

Process finished with exit code 0
类型字符 含义
o 八进制格式。 输出以 8 为基数的数字。

例如:

b = 65
s = '{:o}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
101

Process finished with exit code 0
类型字符 含义
x 十六进制格式。 输出以 16 为基数的数字,使用小写字母表示 9 以上的数码
X 十六进制格式。 输出以 16 为基数的数字,使用大写字母表示 9 以上的数码

例如:

b = 123456
s = '{:x}'.format(b)
print(s)
s = '{:X}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1e240
1E240

Process finished with exit code 0
类型字符 含义
n 数字。 这与 ‘d’ 相似, 不同之处在于它会使用当前区域设置来插入适当的数字分隔字符(这句不懂)
None 和 ‘d’ 相同。

例如:

b = 123456
s = '{:n}'.format(b)
print(s)
s = '{:}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
123456
123456

Process finished with exit code 0
浮点数表示类型
类型字符 含义
e 指数表示。 以使用字母 ‘e’ 来标示指数的科学计数法打印数字。 默认的精度为 6
E 指数表示。 与 ‘e’ 相似,不同之处在于它使用大写字母 ‘E’ 作为分隔字符。

例如:

b = 123456.0
s = '{:e}'.format(b)
print(s)
s = '{:E}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
1.234560e+05
1.234560E+05

Process finished with exit code 0
类型字符 含义
f 浮点数表示。 将数字显示为一个浮点数。 默认的精确度为 6。
F 浮点数表示。 与 ‘f’ 相似,但会将 nan 转为 NAN 并将 inf 转为 INF(这句不懂)

例如:

b = 123456.0
s = '{:f}'.format(b)
print(s)
s = '{:F}'.format(b)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
123456.000000
123456.000000

Process finished with exit code 0
类型字符 含义
g 常规格式。对于给定的精度p, 如果p >= 1, 会将数值舍入到 p 位有效数字,再将结果以浮点数或者科学计数法的形式格式化。
G 浮点数表示。 与 ‘f’ 相似,但会将 nan 转为 NAN 并将 inf 转为 INF(这句不懂)

例如:

# 如果  0 < 数字有效位个数 <= 6,按数字有效位个数输出
a = 12345
s = 'a = {:g}'.format(a)
print(s)
s = 'a = {:G}'.format(a)
print(s)

b = 123456
s = 'b = {:g}'.format(b)
print(s)
s = 'b = {:G}'.format(b)
print(s)
# 如果  0 < 数字有效位个数 <= 6,并且有小数点后跟一个小数位0,则小数点会被省略。
c = 123456.0
s = 'c = {:g}'.format(c)
print(s)
s = 'c = {:G}'.format(c)
print(s)
# 如果  0 < 数字有效位个数 <= 6,并且有小数点后跟一个小数位0,如果整数部分为5个有效数字,则即使小数部分有多个有效位,小数部分也会被省略,只显示整数部分。
cc = 12345.02
s = 'cc = {:g}'.format(cc)
print(s)
s = 'cc = {:G}'.format(cc)
print(s)
# 如果  0 < 数字有效位个数 <= 6,并且有小数点后跟一个小数位0,如果整数部分为5个有效数字,则即使小数部分有多个有效位,小数部分也会被省略,只显示整数部分。
cc = 1234.02
s = 'cc = {:g}'.format(cc)
print(s)
s = 'cc = {:G}'.format(cc)
print(s)

# 如果  数字有效位个数 > 6,它会以科学计算法的形式显示,并保证有6位有数字,被省略的按四舍五入方式进位
d = 123456789
s = 'c = {:g}'.format(d)
print(s)
s = 'c = {:G}'.format(d)
print(s)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
a = 12345
a = 12345
b = 123456
b = 123456
c = 123456
c = 123456
cc = 12345
cc = 12345
cc = 1234
cc = 1234
c = 1.23457e+08
c = 1.23457E+08

Process finished with exit code 0
类型字符 含义
% 百分比。 将数字乘以 100 并显示为浮点 (‘f’) 格式,后面带一个百分号
None 类似于 ‘g’,不同之处在于当使用浮点表示法时,小数点后将至少显示一位。 默认精度与表示给定值所需的精度一样

例如:

total = 22
points = 19
str = 'Correct answers: {:.2%}'.format(points/total)
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Correct answers: 86.36%

Process finished with exit code 0
特定类型的专属格式
import datetime
d = datetime.datetime(2020, 7, 4, 12, 15, 58)
str = '{:%Y-%m-%d %H:%M:%S}'.format(d)
print(str)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
2020-07-04 12:15:58

Process finished with exit code 0

带前缀f或F的字符串格式化

name = 'Fred'
str = f'He said his name is {name!r}.'
print(str)
s = f"He said his name is {repr(name)}."
print(s)

import decimal
width = 10
precision = 4
value = decimal.Decimal("12.34567")
ss = f'result: {value:{width}.{precision}}'
print(ss)

import datetime
today = datetime.datetime(year=2020, month=1, day=27)
d = f'{today:%B %d, %Y}'
print(d)


number = 1024
hex = f"{number:#0x}"
print(hex)

foo = "bar"
f = f"{foo = }"
print(f)


line = "The mill's closed"
l = f"{line = }"
print(l)
l = f"{line = :20}"
print(l)
l = f"{line = !r:20}"
print(l)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
He said his name is 'Fred'.
He said his name is 'Fred'.
result:      12.35
January 27, 2020
0x400
foo = 'bar'
line = "The mill's closed"
line = The mill's closed   
line = "The mill's closed" 

Process finished with exit code 0

printf风格的字符串格式化

语法:

format % values
  • format:
    format是一个格式化字符串,它里面包含若干个转换标记符%,它们会被values中的0个或者多个值替换。
    如果 format 要求一个单独参数,则 values 可以为一个非元组对象。例如:
print('%#x' % 10)

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
0xa

Process finished with exit code 0

否则的话,values 必须或者是一个包含项数与格式字符串中指定的转换符项数相同的元组,或者是一个单独映射对象(例如字典)。例如:

print('%(language)s has %(number)03d quote types.' %{
    
    'language': "Python", "number": 2});

d = {
    
    'language': "Python", "number": 2}
print('%(language)s has %(number)03d quote types.' %d);

print('%#x, %#f, %s, %#x' % (10 , 6.0, 'hello, world', 14500))

其中’%#x, %#f, %s, %#x’就是format, (10 , 6.0, ‘hello, world’, 14500)就是values。
输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Python has 002 quote types.
Python has 002 quote types.
0xa6.000000, hello, world, 0x38a4

Process finished with exit code 0

转换表达式的组成

转换开始字符’%

每个转换表达式都以‘%’开始。

可选的映射键,在圆括号中,如字典的键

print('%(language)s has %(number)03d quote types.' % {
    
    'language': "Python", "number": 2})

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Python has 002 quote types.

Process finished with exit code 0

可选的转换**Flag**,可影响转换的结果

Flag 含义
# 值的转换根据转换符转换成不同的形式

如:

  • 转换符o转换成8进制,加前缀‘0o’。
  • 转换符x/X转换成16进制,加前缀’0x’/‘0X’。
print('%#o, %#x, %#X' % (10, 2222, 21));

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
Python has 002 quote types.
0o12, 0x8ae, 0X15

Process finished with exit code 0
Flag 含义
0 转换时, 将为数字值填充零字符
print('%#05o, %#x, %#X' % (10, 2222, 21))

输出结果(输出宽度包括前缀):

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
0o012, 0x8ae, 0X15

Process finished with exit code 0
Flag 含义
- 将转换的值靠左对齐,如果同时指定了‘0’,则‘0’会被忽略
print('*****   %-#05o, %#x, %#X *********' % (10, 2222, 21))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
*****   0o12 , 0x8ae, 0X15 *********

Process finished with exit code 0
Flag 含义
’ ’ (空格) 符号位转换产生的正数(或空字符串)前将留出一个空格
print('%-#05o, %#x, %#X *********' % (10, 2222, 21))
print('%-# 05o, %#x, %#X *********' % (10, 2222, 21))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
0o12 , 0x8ae, 0X15 *********
 0o12, 0x8ae, 0X15 *********

Process finished with exit code 0
Flag 含义
+ 符号字符 (’+’ 或 ‘-’) 将显示于转换结果的开头(会覆盖 “空格” Flag
print('%-#05o, %#x, %#X *********' % (10, 2222, 21))
print('%-# +05o, %#x, %#X *********' % (10, 2222, 21))
print('%-# +05o, %#x, %#X *********' % (-10, 2222, 21))

输出结果:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/05.py
0o12 , 0x8ae, 0X15 *********
+0o12, 0x8ae, 0X15 *********
-0o12, 0x8ae, 0X15 *********

Process finished with exit code 0

可选的最小字段宽度

可选的精度,在点号(’’.’)加精度值。

可选的长度修饰符

  • h
  • l/L
    长度修饰符 (h, l 或 L),会被忽略,因为对 Python 来说没有必要, 所以,例如 %ld 等价于 %d。

转换类型

转换符 含义
d 有符号十进制整数。
i 有符号十进制整数。
o 有符号八进制数
u 过时类型 – 等价于 ‘d’。
x 有符号十六进制数(小写)。
X 有符号十六进制数(大写)。
e 浮点指数格式(小写)。
E 浮点指数格式(大写)。
f 浮点十进制格式。转换结果总带小数点,默认精度为6
F 浮点十进制格式。
g 浮点格式。 如果指数小于 -4 (如-5,-6)或不小于精度(6)则使用小写指数格式,否则使用十进制格式。
G 同‘g’
r 原始字符串(使用 repr() 转换任何 Python 对象
s 字符串(使用 str() 转换任何 Python 对象)
a 字符串(使用 ascii() 转换任何 Python 对象)
% 不转换参数,在结果中输出一个 ‘%’ 字符

[上一页][下一页]

猜你喜欢

转载自blog.csdn.net/wzc18743083828/article/details/108988214