Python字符串知识点总结

文章目录


字符串(string)

Python字符串是一个不可变的 unicode 字符序列,是Python的基本数据类型之一。


提示:以下是本篇文章正文内容,由小编进行网络整理,版权归原作者所有,如有侵权,请联系本人,本人会第一时间删除处理!

一、字符串的创建

1.1 由单引号、双引号、三对单引号或双引号组成。

'''
单引号 '...'
双引号 "..."
三引号 ''' '''、”“” “”“
'''

示例:

str1 = 'spam eggs'
str2 = "spam eggs"
str3 = '''First line.
Second line.'''
str4 = """First line.
Second line"""
  • 单引号与双引号的同时使用情况:
str5 = '"Yes," they said.'
str6 = "doesn't"

1.2 使用 str() 内置函数来定义字符串或将另一种数据类型转换为字符串

# 字符串
greeting = str('hello world!')
print(greeting) # hello world!

# 浮点型
n = 25.95236
str1 = str(n)
print(str1) # 25.95236

# 列表
s = str([1,2,3,4,(5,6,7),{8,9,0}])
print(s) # [1, 2, 3, 4, (5, 6, 7), {8, 9, 0}]
print(type(s)) # <class 'str'>

# 元组
s1 = str((1,2,3))
print(s1) # (1, 2, 3)
print(type(s1)) # <class 'str'>

# 字典
s1 = str({'a':1,'b':2})
print(s1) # {'a': 1, 'b': 2}
print(type(s1)) # <class 'str'>

# 集合
s1 = str({'a','b','c','d'})
print(s1) # {'d', 'b', 'a', 'c'}
print(type(s1)) # <class 'str'>

二、转义字符和原始字符

2.1 常用转义字符

转义字符说明
\\ (在行尾时)续行符
\r回车符,将光标位置移到本行开头。
\t水平制表符,也即 Tab 键,一般相当于四个空格。
\\反斜杠符号
\’单引号
\"双引号
\f换页

未使用转义字符:
注意:字符串中,遇反斜杠转义字符

print('C:\some\name')  # C:\some
                       # ame

使用转义字符:

print('c:\\some\\name') # c:\some\name

以下这种情况遇到反斜杠不会被转义:

# 注意:最开始的换行没有包括进来
print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

"""
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

2.2 原始字符

字符串一但遇到反斜杠会转义字符,取消转义字符就在字符前面加’r’。

print(r'C:\some\name') # C:\some\name

三、判断字符串

3.1 判断字符串的前缀与后缀

startswith():判断前缀
endswith():判断后缀
前缀:raw_str.startswith(sub_str)
raw_str = "The official home of the Python Programming Language"
star_bool = raw_str.startswith('The')
print(star_bool) # True
后缀:raw_str.endswith(sub_str)
raw_str = "The official home of the Python Programming Language"
end_bool = raw_str.endswith('age')
print(end_bool) # True

3.2 判断子串是否在字符串中

in、not in
in:判断子串在字符串,返回True,否则返回Falsenot in:判断子串不在字符串,返回True,否则返回False

示例:

s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
print('q' in s) # True
print('t' not in s) # False

3.3 判断字符串的类型

A 常用类型:

"""
str.isalnum() # 检测字符串是否是字母、数字组成
str.isalpha() # 检测字符串是否只由字母组成
str.isdigit() # # 检测字符串是否只由数字组成
str.isupper() # 检测字符串中所有的字母是否都为大写
str.islower() # 检测字符串是否由小写字母组成
str.istitle() # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
str.isspace() # 检测字符串是否只由空格组成
"""
A.1 字母、数字组成:isalnum
print('res323'.isalnum()) # True
print('res'.isalnum()) # True
print('1234'.isalnum()) # True
print('res123%$'.isalnum()) # False
A.2 字母组成:isalpha
print('helloworld'.isalpha()) # True 检测字符串是否只由字母组成
print('432323423'.isalpha()) # False
print('while322'.isalpha()) # False
A.3 数字组成:isdigit
print('4253255'.isdigit()) # True
A.4 所有字母都是大写:isupper
res = 'The official home of the Python Programming Language'
print(res.isupper()) # False
print("UPPER".isupper()) # True
A.5 所有字母都是小写:islower
res = 'The official home of the Python Programming Language'
print(res.islower()) # False
print("lower".islower()) # True
A.6 是标题:istitle
res = 'The official home of the Python Programming Language'
print(res.istitle()) # False
print("Hello World".istitle()) # True
A.7 是空格:isspace
res = 'The official home of the Python Programming Language'
print(res.isspace()) # False
print(' '.isspace()) # True
A.8 综合运用例子
sentence = "There are 22 apples"

alphas = 0
digits = 0
spaces = 0

for i in sentence:

    if i.isalpha():
        alphas += 1

    if i.isdigit():
        digits += 1

    if i.isspace():
        spaces += 1

print("一共有", len(sentence), "个字符") # 一共有 19 个字符
print("有", alphas, "个字母") # 有 14 个字母
print("有", digits, "个数字") # 有 2 个数字
print("有", spaces, "个空格") # 有 3 个空格

B 不常用类型

"""
str.isidentifier()
str.isnumeric()
str.isprintable()
str.isdecimal()
str.isascii()
"""
B.1 isidentifier:有效标识符否

由字母、数字、下标线,任意组合为True;不能以数字开头或包含任何空格,其余特殊为False;类似变量的命名规范。

print('1str'.isidentifier()) # False
print('^two'.isidentifier()) # False
print('$two'.isidentifier()) # False

print('one'.isidentifier()) # True
print('_one'.isidentifier()) # True
B.2 isnumeric:只由数字组成,只针对unicode对象
print(u'312321'.isnumeric()) # True
print(u'4324.432'.isnumeric()) # False
print(u'423fv'.isnumeric()) # False
print(u'faads'.isnumeric()) # False
B.3 isdecimal:只包含十进制字符,只针对unicode对象
print(u'42432'.isdecimal()) # True
print(u'42342.424'.isdecimal()) # False
print(u'fasf42324.43'.isdecimal()) # False
print(u'4234.244F'.isdecimal()) # False
B.4 isprintable:所有字符都能打印,就是返回True,有转义字符则为False
print('fsaffaf'.isprintable()) # True
print('if 5>1:print("hell world")'.isprintable()) # True
print('\n\r\nsome\python'.isprintable()) # False
B.5 isascii:检测字符值是否在 7 位 ASCII 集范围内
print('中国'.isascii()) # False
print("123ABC~!@#$%^&*()_\"+{}|:?><;,./".isascii()) # True
print("ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ①②③④⑤⑥⑦⑧⑨⑩一二三四五六七八九十".isascii()) # False
print("ΑΒΓΔΕΖΗΘΙΚ∧ΜΝΞΟ∏Ρ∑ΤΥΦΧΨΩ".isascii()) # False

四、查询字符

4.1 查找索引下标:find(),rfind(),index(),rindex()

find()与index()查找出现的位置(下标),只找第一次出现的位置(下标)

"""
str.find(sub[, start[, end]])
str.lfind(sub[, start[, end]])
str.rfind(sub[, start[, end]])

str.index(sub[, start[, end]])
str.lindex(sub[, start[, end]])
str.rindex(sub[, start[, end]])
"""
find()与rfind()
# find()
s = 'spam'
print(s.find('p')) # 1

raw_str = "你讨厌的人,正在努力"
index = raw_str.find('人')
print(index) # 4

raw_str = 'abbbcccbbba'
index = raw_str.find('b')
print(index) # 1

# rfind()
raw_str = 'abbbcccbbba'
index = raw_str.rfind('b')
print(index) # 9

# find()方法,找不到时,返回-1
raw_str = "bbbcccdddd"
index = raw_str.find('a')
print(index) # -1
index()与rindex()
# index()
raw_str = "你讨厌的人,正在努力"
index = raw_str.index('力')
print(index) # 9

# rindex()
raw_str = 'abbbcccbbba'
index = raw_str.rindex('b')
print(index) # 9

# index()方法,找不到时,会报错
raw_str = 'abbbcccbbba'
# index = raw_str.index('u') 报错

4.2 for循环

Python字符串是一个个字符组成的序列。你可以使用for循环来遍历每个字符。

  • 第一种方法:(推荐使用)
raw_string = "Python.org"
for item in raw_string:
    print(item)
  • 第二种方法:
raw_string = "Python.org"
for i in range(len(raw_string)):
    print(raw_string[i])

4.3 长度:len()

raw_str = "Welcome to Python.org"
print(len(raw_str)) # 21

4.4 统计数量:count()

str.count(sub_str,start,end)

raw_str = "Welcome to Python.org"
print(raw_str.count('o')) # 4
# 设置start,查找起始点
raw_str = "The official home of the Python Programming Language"
count = raw_str.count('o',13,len(raw_str))
print(count) # 4

4.5 最大值、最小值:max(),min()

按ASII码对照表,求最大值、最小值

# max(x)
str = "this is really a string example....wow!!!"
print("最大字符:"+max(str)) # 最大字符:y,其ASCII码是121

# min(x)
str = "this-is-real-string-example....wow!!!"
print("最小字符: " + min(str)) # 最小字符: !,其ASCII码是33

五、处理字符(类似修改,但原字符串不变)

5.1 连接(拼接)字符

5.1.1 拼接字符:+

word = 'Python'
print(word+'...') # Python...

5.1.2 相邻字符连接起来:"…" “…”

相邻的两个或多个字符串字面值(引号引起来的字符)将自动连接到一起

print('py' 'thon') # python
print('Put several strings within parentheses '
      'to have them joined together.') # Put several strings within parentheses to have them joined together.

注意:以下几种情况会报错。

prefix = 'Py'
# print(prefix 'thon') # 报错,不能是变量
# print(('um' * 3) 'ium') # 报错,不能是表达式
# print((prefix * 3) 'ium') # 报错,不能是变量表达式

5.1.3 重复字符串(乘积):*

print('A'*3) # AAA

5.2 索引与切片

A 索引

1.截取单个字符:
word = 'Python'
print(word[0]) # P
print(word[3]) # h
print(word[-1]) # n
print(word[-3]) # h
2.截取整个字符串:
word = 'Python'
print(word[:]) # Python
print(word[::]) # Python
print(word[::-1]) # nohtyP

B 切片

1.索引切片:[start : end : step]
  • step步长为正数,start<end,结果不为空,start>end,结果为空。start、end为空或一正一负,则不遵守这条定理。
word = 'Python'
print(word[1:7]) # ython
print(word[1:300]) # ython,顾头不顾尾
print(word[1:]) # ython
print(word[:6]) # Python
print(word[2:6:2]) # to,步长为正数,顺序
print(word[1:-3]) # yt,步长1,start>end 除外,不为空
print(word[4:1]) # 空,步长1,start>end 为空
print(word[-1:-5]) # 空,步长1,stat>end 为空
print(word[-1:4]) # 空,步长1,start<end 除外,不为空
print(word[-5:]) # ython,步长为正数1,从左向右截取数据,start与end按照从右向左看
print(word[-5:-1]) # ytho,步长为正数1,从左向右截取数据,start与end按照从右向左看
print(word[:-4]) # Py,步长为正数1,从左向右截取数据,start与end按照从右向左看
  • step步长为负数,start>end,结果不为空,start<end,结果为空。start、end为空或一正一负,则不遵守这条定理。
word = 'Python'
print(word[1:4:-1]) # 空
print(word[-4:-1:-1]) # 空
print(word[:1:-1]) # noht,步长为负数,从右向左切片,切片到从左到右索引下标是1的位置
print(word[2::-1]) # tyP,步长为负数,从右向左切片,开始切片于从左到右索引下标为2的位置,一直到最左侧字符
print(word[-1:-5:-1]) # noht,步长为-1,从右向左截取数据,倒序
print(word[:-5:-1]) # noht
print(word[-5::-1]) # yP,步长为-1,从右向左截取数据,end值没有填默认最值
print(word[5:2:-1]) # noh
print(word[5:-4:-1]) # noh
print(word[-1:3:-1]) # no
2.split切片

四种方法:split()、lsplit()、rsplit()、splitlines()

"""
切片常用方法:
str.split(sep=None, maxsplit=-1):sep分割符号,maxsplist最大切割次数
str.lsplit(sep=None, maxsplit=-1):sep分割符号,maxsplist最大切割次数
str.rsplit(sep=None, maxsplit=-1):sep分割符号,maxsplist最大切割次数
str.splitlines([keepends]):keepends意思是保留,它为False或空则不保留换行符,它为True则保留

其它知识:
\n  换行
\r  回车
\r\n    回车+换行
\r\n    回车+换行
"""
  • 默认从左向右切片:split()方法、lsplit()方法
# 空格
raw_str = "The official home of the Python Programming Language"
ls = raw_str.split()  # 默认按空格方式切片
# ls1 = raw_str.split(' ') # 跟上行代码一样的效果
print(ls)  # ['The', 'official', 'home', 'of', 'the', 'Python', 'Programming', 'Language']

# 逗号
line = 'aa,bb,cc'
print(line.split(','))  # ['aa', 'bb', 'cc']

# 特殊分割符:|
mysql_user1 = "admin|123|普通管理员"
print(mysql_user1.split('|'))
  • 从右向左切片:rsplit()
print('Monty Python'.rsplit('t'))  # ['Mon', 'y Py', 'hon']
print('Monty Python'.rsplit('t', 1))  # ['Monty Py', 'hon']
  • 设置切片的最大次数:默认maxsplit=-1,等号右边可改为想切割的次数:split()
# 字符串为分割符
raw_str = "The official home of the Python Programming Language"
ls = raw_str.split('the', maxsplit=2)
print(ls)  # ['The official home of ', ' Python Programming Language']

# 特殊符号|为分割符
mysql_user2 = "root|root是超级管理员"
print(mysql_user2.split('|', maxsplit=1)) # ['root', 'root是超级管理员']
mysql_user3 = "aaa|123|普通用户"
print(mysql_user3.rsplit('|', 1)) # ['aaa|123', '普通用户']
  • 显性换行符,分割:split()与split("\n")效果一样
s = 'a\nb\nc'
print(s.split()) # ['a', 'b', 'c']
print(s.split("\n")) # ['a', 'b', 'c'] 
  • 隐性换行符,分割:split(’\n’)
    此方法可应用在三对单、双引号(类似文档注释的多行注释)
"""
注意:三对引号的首尾都换行,换行分割后,一定含两个空字符串
			(即首部一个空字符串,尾部一个空字符串)
"""
raw_str = """从前的歌谣
都在指尖绕
得不到的美好
总在心间挠
白饭粒无处抛
蚊子血也抹不掉
触不可及刚刚好
......"""
ls = raw_str.split('\n')
print(ls) # ['从前的歌谣', '都在指尖绕', '得不到的美好', '总在心间挠', '白饭粒无处抛', '蚊子血也抹不掉', '触不可及刚刚好', '......']
	      # 这里,三对双引号的首尾都没有换行,结果不含两个空字符串
  • 隐性换行符,分割:splitlens()
    此方法常应用在三对单、双引号(类似文档注释的多行注释)
print("".splitlines())  # []
print("One line\n".splitlines())  # ['One line']
  • 注意1:将字符串全部一刀切片,返回含两个空字符串的列表:split()
raw_str = "冰雪消融大地春,山中溪流响叮咚"
ls = raw_str.split("冰雪消融大地春,山中溪流响叮咚")
print(ls)  # ['', '']

扩展(面试题):判断含两个空字符串的布尔值:

print(bool(["", ""]))  # True,列表有两个空字符串,列表中有东西就行
print(bool([""]))  # True,列表有两个空字符串,列表中有东西就行
  • 注意2:maxsplit>raw_str,即切刀的长度长于原字符串,返回原字符串:split()
raw_str = '春光明媚艳阳照'
ls = raw_str.split('春光明媚艳阳照,春回大地风景好') # maxsplit超出原字符串的长度,返回原字符串
print(ls) # ['春光明媚艳阳照']

5.3 字母的大小写转换

str.upper()
str.lower()
str.title()

str.capitalize()

str.swapcase()
str.casefold()
1.转换大写、小写、标题、首字母大写
res = "hi,my nAme IS PYtHon"
print(res.upper()) # 所有区分大小写的字符,转换为大写
print(res.lower()) # 所有区分大小写的字符,转换为小写
print(res.title()) # 每个单词第一个字母为大写,其余字母为小写
s = 'Twos-Complement Numbers.'
print(s.title()) # Twos-Complement Numbers. # 连接符(-)后面的单词,首字母大写
print(res.capitalize()) # 首个字符大写,其余为小写
2.大写转小写,小写转大写
print('Hello World'.swapcase()) # hELLO wORLD 大小写互相转换
3.清除大小写,转换成小写(不常用)

返回原字符串消除大小写的副本。 消除大小写的字符串可用于忽略大小写的匹配。
消除大小写类似于转为小写,但是更加彻底一些,因为它会移除字符串中的所有大小写变化形式。 例如,德语小写字母 ‘ß’ 相当于 “ss”。

res1 = 'The official hoMe of the Python PrograMming Language'
print(res1.casefold()) # the official home of the python programming language
s = "БBß" # 俄美德
print(s.lower()) # бbß
print(s.casefold()) # бbss
4.实例运用:

校验用户输入的验证码是否合法:

verify_code = "abDe"
user_verify_code = input("请输⼊验证码:").strip()
if verify_code.upper() == user_verify_code.upper():
	print("验证成功")
else:
	print("验证失败")

5.4 指定编码格式:str.encode(GBK)

str.encode([encoding=“utf-8”][,errors=“strict”]),中括号可以省略,默认采用 utf-8 编码

str1 = "编程语言"
str2 = "python.org"
# utf8编码
print("utf8编码:",str1.encode(encoding="utf8",errors="strict")) #等价于print("utf8编码:",str1.encode("utf8"))
print("utf8编码:",str2.encode(encoding="utf8",errors="strict"))
# gb2312编码
print("gb2312编码:",str1.encode(encoding="gb2312",errors="strict"))#以gb2312编码格式对str1进行编码,获得bytes类型对象的str
print("gb2312编码:",str2.encode(encoding="gb2312",errors="strict"))
# cp936编码
print("cp936编码:",str1.encode(encoding="cp936",errors="strict"))
print("cp936编码:",str2.encode(encoding="cp936",errors="strict"))
# gbk编码
print("gbk编码:",str1.encode(encoding="gbk",errors="strict"))
print("gbk编码:",str2.encode(encoding="gbk",errors="strict"))
print('GBK编码:',str1.encode('GBK'))

5.5 去除空白或字符:strip、lstrip、rstrip

去除字符串两侧的字符或空白:strip()

res = ' hello world!   '
print(res.strip()) # hello world!

url = 'www.baidu.com'
print(url.strip('cmow.')) # baidu

去除左侧或右侧的字符或空白:左lstrip()、右rstrip()

res1 = '\t\t\n hello world!'
print(res1.lstrip()) # hello world!
res2 = 'aaa,bbb,ccc,ddd\n'
print(res2.rstrip()) # aaa,bbb,ccc,ddd

url = 'www.baidu.com'
print(url.lstrip('w.')) # baidu.com
print(url.rstrip('cmo.')) # www.baidu

5.6 替换:replace()

s = 'spam!spam1'
print(s.replace('1','!')) # spam!spam! 	

raw_str = "Quick & Easy to Learn"
str = raw_str.replace("&","and")

a = "I saw a wolf in the forest. A lonely wolf."
b = a.replace("wolf", "fox")
  • 设置替换次数(从左向右):
raw_str = "Great software is supported by great people."
str = raw_str.replace('o','<0>',2)
print(str) # Great s<0>ftware is supp<0>rted by great people.

a = "I saw a wolf in the forest. A lonely wolf."
c = a.replace("wolf", "fox", 1) # 只替换第一个出现
print(c) # I saw a fox in the forest. A lonely wolf.

5.7 替换制表符:expandtabs()

s = "01\t012\t0123\t01234"
print(s.expandtabs()) # 01      012     0123    01234

5.8 填充字符:zfill

"""
str.zfill(width): 填充字符串,使其长度变为width,包含正负符号
"""
print('42'.zfill(5))# 00042
print('-42'.zfill(5)) # -0042

5.9 字符串对齐方式:ljust、rjust、center

  • 语法:
str.ljust(width[, fillchar]):字符串左对齐,不够宽度则用fillchar填充
str.rjust(width[, fillchar]):字符串右对齐,不够宽度则用fillchar填充
str.center(width[, fillchar]):字符串居中,不够宽度则用fillchar填充
  • 左对齐、右对齐:ljust、rjust
str = "this is string example....wow!!!"
print(str.ljust(40)) # this is string example....wow!!!        
# 字符串左对齐:
print(str.ljust(40,'*')) # this is string example....wow!!!********
# 字符串右对齐:
print(str.rjust(40,'*')) # ********this is string example....wow!!!
  • 居中:center
s = 'hello'
print(s.center(20,'*')) # *******hello********

5.10 添加连接符:join

  • 语法
str.join(iterable):常用于从字符串列表中创建一个字符串
# 列表
res_list = ['中国', '美国', '英国']
print('|'.join(res_list))  # 中国|美国|英国
# 字符串
raw_str = 'Welcome'
new_str = "/".join(raw_str)
print(new_str) # W/e/l/c/o/m/e
# 元组
seq = ('1','5','6','8','8','8','7','8','8','8','7')
new_str = ''.join(seq)
print(new_str) # 15688878887
# 集合
raw_set = {'aaa','bbb','ccc','ddd'}
str = '-'.join(raw_set)
print(str) # aaa-ddd-ccc-bbb
# 字典
raw_dict = {'a':1,'b':2,'c':3}
str = '-'.join(raw_dict)
print(str) # a-b-c

删除列表逗号和方括号,即将列表的所有元素用空格连接起来:

# 将列表所有字符串元素用空格连接起来
arr = ['sunday', 'monday', 'tuesday', 'wednesday']

# 方法一:不使用星号
print(' '.join(map(str, arr))) # sunday monday tuesday wednesday

# 使用函数的convolution来删除逗号和方括号,使用前缀*可以解决解包时的问题
# 方法二:使用星号
print(*arr) # sunday monday tuesday wednesday

5.11 使用指定分隔符分割字符串:partition、rpartition

这两个方法类似split()方法,不过找到第一个分隔符就分割,而且分隔符也切割出来,结果用元组储存起来。
返回值:返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

  • str.partition(sub_str):从左向右
str = 'http://www.baidu.com'
s = str.partition('.')
print(s) # ('http://www', '.', 'baidu.com')

s = str.partition(' ')# 如果换成None或""为分隔符,会报错
print(s)  # ('http://www.baidu.com', '', '')

s = "1 + 2 + 3 = 6"
a = s.partition("=")
print(a) # ('1 + 2 + 3 ', '=', ' 6')
  • str.rpartition(sub_str):从右向左
str = 'http://www.baidu.com'
s = str.rpartition('.')
print(s) # ('http://www.baidu', '.', 'com')
# s = str.rpartition("") 分隔符为任意字符串、None、""都会报错

5.12 翻译:maketrans和translate结合使用

# 创建字符映射的转换表,类似字典(翻译对照表)
intab = 'aeiou'
outtab = '12345'
trantab = str.maketrans(intab,outtab)
# 根据字典映射翻译字符串
str = 'this is string example....wow!!!'
print(str.translate(trantab))

5.12 反转(倒转)字符串

  • 方法一:反向切片法
str = "Welcome to Python Examples."
# 使用用切片法反转字符串
reversed = str[::-1]  # 反转字符
# 打印反转后的字符串
print(reversed)
  • 方法二:for循环反转字符串
str = "Welcome to Python Examples."
# 使用用for循环倒转(反转)字符串
reversed = ''  # 用于存储反转后的字符串
for c in str:
    reversed = c + reversed  # 由左向右遍历字符串,并将遍历到的字符添加到左边
# 打印反转后的字符串
print(reversed)
  • 方法三:while循环反转字符串
str = "Welcome to Python Examples."
# 使用while循环倒转(反转)字符串
reversed = ''  # 用于存储反转后的字符串
length = len(str) - 1
while length >= 0:
    reversed = reversed + str[length]
    length = length - 1
# 打印反转后的字符串
print(reversed)
  • 方法四:使用list.reverse()反转字符串
str = "Welcome to Python Examples."
# 将字符串转换为字符列表
str_list = list(str)
# 反转列表
str_list.reverse()
# 加入列表项
reversed = ''.join(str_list)
# 打印反转后的字符串
print(reversed)

六、格式化字符串

6.1 百分比:%

  • 辅助格式化符号
"""
-: 指定格式化字符串宽度时,左对齐
+:对正数输出正值符号”+“,且右对齐
#:在八进制数前加0o,在十六进制前显示0x
m,n: m是显示的最大总宽度,n是小数点后的位数,小数点数四舍五入
"""
print("%-d" % 43) # 43,没有指定宽度
print("%-5d" % 43)  # "43   ",-表示左对齐,数字5在格式化符号中指字符串总宽度是5位
print("%+5d" % 32)  # "  +32",+表示”+“号,数字5在格式化符号中指字符串总宽度是5位
print("%+05d" % 32)  # +0032,0表示是不足宽度用0填补
print("%+ 5d" % 32)  # +"  +32",+后的空格表示是不足宽度用空格填补
print("%7.2f" % 42.7809)  # "  42.78",m是7,表示为总宽度,n是2表示小数点后两位,小数点数四舍五入
print("%#o" % 87)  # 0o127,十进制转换为八进制打印出来,并在结果前加上前缀”0o“
print("%#x" % 87)  # 0x57,十进制转换为十六进制打印出来,并在结果前加上前缀”0x“
print("%#6x" % 87)  # "  0x57"
print("%#-6x" % 87)  # "0x57  "
  • 单个参数传入
str = 'world!'
print("hello %s" % str) # hello world!

%格式字符串时,字符串中有%特殊号,要填两个%特殊符号:

print('%d年利121%%'%(2)) # 2年利润121%,注意:%符号是英文符号,不是中文符号
print('百度第四季度总营收为人民币%d亿元,与上年同期相比增长%d%%'%(303,5)) # %符号是英文符号,不是中文符号
  • 多个参数传入

-1- 元组(推荐使用)

print("Welcome to %s.%s" % ("Python","org")) # Welcome to Python.org
print("我叫%s,今年%d岁,身高%.2f米,体重%.2f公斤" % ('张三', 23, 1.7889, 61.4234)) # 我叫张三,今年23岁,身高1.79米,体重61.42公斤
print("Web Development: %s, %s, %s, %s, %s, %s"%("Django","Pyramid","Bottle","Tornado","Flask","web2py"))# Web Development: Django, Pyramid, Bottle, Tornado, Flask, web2py

-2- 字典:printf风格的字符串格式化(不推荐使用)
当右边的参数为一个字典(或其他映射类型)时,字符串中的格式 必须 包含加圆括号的映射键,对应 ‘%’ 字符之后字典中的每一项。

print('%(name)s今年%(age)d岁.' % {'name': '李世民', 'age': 20})  # 李世民今年20岁.
print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2}) # Python has 002 quote types.

6.2 format()方法

(1)按位置访问参数

print('hello {}'.format("world")) # hello world
print('{},{},{}'.format('a', 'b', 'c'))  # a,b,c
print('{},{},{}'.format('a', 'b', 'c'))  # a,b,c
print('{2},{1},{0}'.format('a', 'b', 'c'))  # c,b,a
print('{2},{1},{0}'.format(*'abc'))  # c,b,a
print("{0}{1}{0}".format('aaa', '--'))  # aaa--aaa,可以重复

(2)按名称访问参数

  • 关键字参数
"""
latitude:纬度
longitude:经度
"""
print('坐标:{latitude},{longitude}'.format(latitude='37.24N', longitude='-115.81w')) # 坐标:37.24N,-115.81w
  • 字典
coord = {'latitude': '37.24N', 'longitude': '-115.81w'}  # 坐标:37.24N,-115.81w
print('坐标:{latitude},{longitude}'.format(**coord))  # 坐标:37.24N,-115.81w

(3)访问参数的项(下标)

coord = (37.24, -115.81)
print('X:{0[0]}N,Y:{0[1]}W'.format(coord))  # X:37.24N,Y:-115.81W

(4)访问参数的属性

# 复数 = real + imag * j
print('复数为:{0},复数实部:{0.real},复数虚部:{0.imag}'.format(7 - 2j))  # 复数为:(7-2j),复数实部:7.0,复数虚部:-2.0

(5)!s替代%s 、!r替代%r

path = "c:\name"
# 遇到转义字符会转义
print("%s" % path)
print("{!s}".format(path))
# 原字符输出
print("%r" % path)
print("{!r}".format(path))
""" 输出:
c:
ame
c:
ame
'c:\name'
'c:\name'
"""
print('{!r}等价于repr()或%r,{!s}等价于str()或%s'.format('c:\name', 'D:\name'))
""" 输出:
'c:\name'等价于repr()或%r,D:
ame等价于str()或%s
"""

(6)替代%x 和%o以及转换基于不同进位制的值

print("int:{0:d},hex:{0:x},oct:{0:o},bin:{0:b}".format(42)) # int:42,hex:2a,oct:52,bin:101010
print("int:{0:d},hex:{0:#x},oct:{0:#o},bin:{0:#b}".format(42)) # int:42,hex:0x2a,oct:0o52,bin:0b101010

(7)使用逗号作为千位分隔符

print('{:,}'.format(1234567890))  # 1,234,567,890
print('{:,.2f}'.format(299699.2567)) # 299,699.26
print(format(3231412414141224.42432,',')) # 3,231,412,414,141,224.5 返回千分位分隔符,常用于货币中
print(format(42424243525.523254363326,'0,.2f')) # 42,424,243,525.52

(8)表示为百分数

print("19/22的正确答案:{:.2%}".format(19 / 22))  # 19/22的正确答案:86.36%

(9)扩展内容:格式化数字

print('%d年利润1%%'%(12)) # 12年利润1%
print('%.2f | %+05d' % (3.14159,-42)) # 3.14 | -0042

(10)对齐文本以及指定宽度:

  • 左对齐:{:[fill]<width}
# < :小于,左对齐
print('{:<20}'.format('左对齐'))  # 左对齐                 
print('{:*<20}'.format('左对齐')) # 左对齐*****************
  • 右对齐:{:[fill]>width}
print('{:>20}'.format('右对齐'))  #                  右对齐
print('{:->20}'.format('右对齐')) # -----------------右对齐
  • 居中:{:[fill]^width}
print('{:^20}'.format('居中'))  #          居中         
print('{:*^20}'.format('居中'))  # *********居中*********
  • 集成左对齐、右对齐和居中——嵌套参数以及更复杂的示例:
for align, text in zip('<^>', ['left', 'center', 'right']):
    print('{0:{fill}{align}16}'.format(text, fill=align, align=align))
"""输出:
left<<<<<<<<<<<<
^^^^^center^^^^^
>>>>>>>>>>>right
"""

(11)格式化时间

import datetime

d = datetime.datetime(2021, 8, 26, 13, 33, 12)
print("{:%Y-%m-%d %H:%M:%S}".format(d))  # 2021-08-26 13:33:12

6.3 f-string:格式字符串字面值

  • 原字符输出
    '!r’调用repr()转化,即先转换,再格式化
name = 'Fred'
print(f'He said his name is {name!r}')  # He said his name is 'Fred'
print(f'He said his name is {repr(name)}')  # He said his name is 'Fred'
  • 字符串
name = 'Fred'
print(f'He said his name is {name}')  # He said his name is Fred

注意:花括号内使用的引号,与花括号外的引号定界符不能冲突,否则会报错。

print(f"I am {'huang wei'}") # I am Huang wei
print(f'''I am {'Huang wei'}''') # I am Huang wei
print(f"""I am {"Huang Wei"}""") # I am Huang wei
print(f'I am {"Huang Wei"}') # I am Huang wei
# print(f"I am {"Huang Wei"}") # 报错

输出花括号{},只需要输入两个花括号即可。

print(f"{{'huang wei'}}") # {'huang wei'}
  • 数字类型
double = 292.1263
print(f'价格:{double:.2f}') # 价格:292.13
  • lambda表达式
a = 123.456
print(f"lambda表达式:{(lambda x:x*5-2)(a):.2f}") # lambda表达式:615.28
"""
f'{(lambda x:x*5-2)(a):.2f}'
说明:注意语法格式的写法,
第一个小括号表示的是lambda表达式,
第二个小括号表示给lambda表达式传入参数。
"""

6.4 template模板格式化

(1)单行字符串

from string import Template

s = Template('$who likes $what')
str = s.substitute(who='tim', what='kung pao')
print(str) # tim likes kung pao
  • 增加异常处理
import string

values = {'var':'foo'}
# 创建字符串模板
t = string.Template("$var is here but $missing is not provided")

try:
	# 因字典缺少missing变量值,故此行代码报错,执行异常处理代码except
    print('substritute()    :',t.substitute(values))
except KeyError as err: # 异常处理分支
    print('ERROR:',str(err)) # values字典中没有missing的值,所有报错,ERROR: 'missing'
    
print('safe_substitute():',t.safe_substitute(values)) # safe_substitute(): foo is here but $missing is not provided

"""程序运行结果:
ERROR: 'missing'
safe_substitute(): foo is here but $missing is not provided
"""

(2)多行字符串
方法一:

from string import Template

s = Template("""用户名:$username
密 码:$userpwd""")
str1 = s.substitute(username='admin', userpwd='123456')
print(str1)
"""输出:
用户名:admin
密 码:123456
"""

方法二:

import string

values = {'var': 'foo'}
t = string.Template("""
    Variable:$var
    Escpe:$$
    Variable in text:${var}iable
""")
print('Template(模块):',t.substitute(values))
"""输出
Template(模块): 
    Variable:foo
    Escpe:$
    Variable in text:fooiable
"""

6.5 format_map()方法

str.format_map(mapping)

class Default(dict):
    def __missing__(self, key):
        return key
print("{name} was born is {contry}".format_map(Default(name='Guido'))) 
# Guido was born is contry
  • 19
    点赞
  • 138
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值