文章目录
- 前言
- 一、字符串的不同表现形式
- 二、字符串访问形式
- 三、字符串的基础应用
- 四、字符串内置函数
- 五、字符串常用方法
- 1.转换(capitalize()/casefold()/lower()/upper()/title()/swapcase())
- 2.搜索(count()/find()/index()/rfind()/rindex())
- 3.以string开头/结尾(startswith()/endswith())
- 4.编码、解码(string.encode()/bytes.decode())
- 5.填充对齐(center()/ljust()/rjust()/zfill())
- 6.删除左/右指定字符(lstrip()/rstrip()/strip())
- 7.判断字符串(isspace()/isprintable()/isidentifier()/isalnum()/isalpha()/isdigit()/isnumeric()/isdecimal())
- 8.格式化字符串指定值(format())
- 9.拆分、截取(split()/rsplit()/splitlines())
- 10.拆分字符串,返回元组(partition()/rpartition())
- 11.字符串转换(maketrans()/translate())
- 12.连接(join())
- 13.字符串替换(replace())
- 14.Tab转换(exandtabs())
前言
字符串是python中最常用的数据类型,下面主要介绍字符串的使用方法。本文内容是参考文章https://blog.csdn.net/m0_70885101/article/details/126087718,建议直接点击原博文查看。
一、字符串的不同表现形式
用引号引起来的就是字符串。
可用:单引号、双引号、三引号
trvar1 = 'abc'
strvar2 = "lily's"
strvar3 = '''
hello
world
!
'''
print (strvar1,type(strvar1))
print (strvar2,type(strvar2))
print (strvar3,type(strvar3))
‘’ 和 " " 和 ‘’’ ‘’’ 都可以表示字符串
对于一些带’的英文语句,用""更加方便
对于要换行的英文语句,用’‘’ ‘’'更加方便
二、字符串访问形式
1.下标索引访问
- str_name[i]
s="Hello,World!"
s=s[6]
正向索引:从第一个(下标0)开始、第二个(下标1)…
反向索引:从倒数第一个(下标-1)、倒数第二个(下标-2)…
2.切片访问
str_name[start : end : step]
s="Hello,World!"
s=s[:6]
参考文章:python切片
3.for循环遍历字符串
使用 for 循环遍历字符串时,将会输出字符串中的每一个字符。
a="hello,world!"
for i in a:
print(i)
4.检查元素是否存在
如果我们需要确定在一个字符串中,是否存在相同的字符或者子字符串,可以使用运算符中的 in 和 not in 关键字。
关键字 | 描述 |
---|---|
in | 如果字符串中包含给定的字符返回True,反之,返回False。 |
not in | 如果字符串不包含给定的字符返回True,反之,返回False。 |
a="hello,world!"
print(a in ',')
print(a not in ',')
三、字符串的基础应用
1.字符串更新
a="hello,world!"
print(a[:6]+'Python!')
2.字符串连接(合并/复制)
同列表和元组一样,字符串之间可以使用+号实现字符串的连接(合并),用*号实现字符串的复制,可以生成一个新的字符串。
a="hello"
b="world"
print(a+b)
a="hello"
print(a*5)
3.打印原始字符 r/R
元字符串 (r/R)+字符串==>表示不转字符,原型化输入字符串。(相当于字符串中给所有特殊意义的字符加了转义符)
print(r"C:\Users")
print(R"C:\Users")
4.格式化字符串
format_string%(argument_to_convert)
python支持格式化字符串输出, 将一个值插入到一个有字符串格式符%s的字符串中。
print("my name is %s,I’m %d" %('lily',21))
python字符串格式化符号如下表所示:
符号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整数 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数,可指定小数点后的精度 |
%e | 用科学计数枨化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f和%E的简写 |
%p | 用十六进制数格式化变量的地址 |
f-string
f 前缀表示格式化字符串,它用于在字符串中嵌入表达式的值。在格式化字符中,f开头,后面跟着字符串,字符串中的变量或表达式可以使用大括号{}来引用,并将其值插入字符串中。
name="lily"
age=18
print(f"my name is {name},I’m {age}")
# 输出:
# my name is lily,I’m 18
print(f'{1+2}')
# 输出:
# 3
info={"name":"lily","age":"18"}
print(f'my name is {info["name"]},I’m {info["age"]}')
# 输出:
# my name is lily,I’m 18
x = 1
print(f'{x + 1}')
# 输出:
# 2
y = 1
print(f'{x + y = }')
# 输出:
# x + y = 2
这种方法更加方便,不用再去判断使用%s还是%d。
format_string.format(argument_to_convert)
格式化字符串的函数str.format()可以参考链接:https://blog.csdn.net/sodaloveer/article/details/134133286
5.字节字符串
b-string
b前缀表示字节字符串,它用于处理二进制数据,而不是文本数据。字节字符串是不可变的,通常用于处理图像、音频、网络协议等二进制数据。
binary_data = b'\x48\x65\x6c\x6c\x6f' # b前缀表示字节字符串,每个\x后面跟着两个十六进制数字
print(binary_data)
# 输出:
# b'Hello'
text="hello"
binary_data=b"hello"
print(type(text))
# 输出:
# <class 'str'>
print(type(binary_text))
# 输出:
# <class 'bytes'>
字符串和字节字符串是不同的数据类型,字符串用于文本,字节字符串用于二进制数据。
6.Unicode字符串
u前缀表示Unicode字符串,它用于处理Unicode编码的文本数据。在Python3中,所有的字符串都是Unicode字符串,因此很少需要使用u前缀。在Python2中,u前缀用于表示Unicode字符串。
unicode_text=u"你好,世界!"
print(unicode_text)
四、字符串内置函数
len()返回字符串长度
a="hello"
print(len(a))
str()转换字符串类型
- 整数转为字符串
a=123
res=str(a)
print(res,type(res))
- 浮点数转为字符串
a=1.23
res=str(a)
print(res,type(res))
- 逻辑运算符转为字符串
a=True
res=str(a)
print(res,type(res))
- 复数转为字符串
a=3-91j
res=str(a)
print(res,type(res))
- 列表转为字符串
a=[1, 2, 3]
res=str(a)
print(res,type(res))
- 元组转为字符串
a=(1, 2, 3)
res=str(a)
print(res,type(res))
- 字典转为字典串
a= {1: 'a', 2: 'b'}
res=str(a)
print(res,type(res))
- 集合转为字符串
a={1, 2, 3}
res=str(a)
print(res,type(res))
五、字符串常用方法
1.转换(capitalize()/casefold()/lower()/upper()/title()/swapcase())
方法 | 描述 |
---|---|
string.capitalize() | 将字符串的第一个字母变大写,其他字母变小写。 |
string.casefold() | 返回一个字符串,其中所有字符均为小写。 |
string.lower() | 转换字符串中所有大写字符为小写(符号和数字将被忽略)。 |
string.upper() | 将字符串中的小写字母转为大写字母(符号和数字将被忽略)。 |
string.title() | 返回"标题化"的字符串,就是说所有单词的首个字母转化为大写,其余字母均为小写。 |
string.swapcase() | 用于对字符串的大小写字母进行转换,即将大写字母转换为小写字母,小写字母会转换为大写字母。 |
str1="hello world!"
str1.capitalize()
# 输出:
# 'Hello world!'
str1="Hello World!"
str1.casefold() #与lower()方法相似,但是比lower()方法强大。
# 输出:
# 'hello world!'
str1="Hello World!"
str1.lower()
# 输出:
# 'hello world!'
str1="hello world!"
str1.upper()
# 输出:
# 'HELLO WORLD!'
str1="hello world!"
str1.title()
# 输出:
# 'Hello World!'
str1="Hello World!"
str1.swapcase()
# 输出:
# 'hELLO wORLD!'
2.搜索(count()/find()/index()/rfind()/rindex())
- string.count(value,start,end)
统计字符串里某个字符出现的次数,可选参数为字符串搜索开始与结束位置。
参数 | 描述 |
---|---|
value | 必需,字符串。要检索的字符串。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello world!"
print(a.count("o",2,9))
# 输出:
# 2
- string.find(value,start,end)
从左开始检测字符串中是否包含子字符串 str, 如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回 -1。
参数 | 描述 |
---|---|
value | 必需。要检索的字符串。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello world!"
print(a.find("o",2,9))
# 输出:
# 4
a="hello world!"
print(a.find("o",6,10))
# 输出:
# 7
a="hello world!"
print(a.find("a"))
# 输出:
# -1
- string.index(value,start,end)
从左开始检测字符串中是否包含子字符串 str,与 find() 方法一样,只不过如果str不在 string中会报一个异常。
参数 | 描述 |
---|---|
value | 必需。要检索的字符串。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello world!"
print(a.index("o",2,9))
# 输出:
# 4
a="hello world!"
print(a.index("o",6,10))
# 输出:
# 7
a="hello world!"
print(a.index("a"))
# 输出:
# ValueError: substring not found
注意: find()与index()区别
- string.rfind(value,start,end)
从右开始检测并返回字符串最后出现的位置,如果没有匹配项则返回 -1 。
参数 | 描述 |
---|---|
value | 必需。要检索的字符串。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello world!"
print(a.rfind("o"))
# 输出:
# 7
a="hello world!"
print(a.rfind("o",5,10))
# 输出:
# 7
a="hello world!"
print(a.rfind("a"))
# 输出:
# -1
- string.rindex(value,start,end)
从右开始检测并返回字符串 str 在字符串中最后出现的位置,与 rfind() 方法一样,只不过如果没有匹配的字符串会报异常。
参数 | 描述 |
---|---|
value | 必需。要检索的字符串。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello world!"
print(a.rindex("o",2,9))
# 输出:
# 7
a="hello world!"
print(a.rindex("o",6,10))
# 输出:
# 7
a="hello world!"
print(a.rindex("a"))
# 输出:
# ValueError: substring not found
注意: rfind()与rindex()区别
3.以string开头/结尾(startswith()/endswith())
- string.startswith(value,start,end)
判断字符串是否以指定字符串开头,如果是则返回 True,否则返回 False。
参数 | 描述 |
---|---|
value | 必需。检查字符串是否以某个字符串开头。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello,world!"
print(a.startswith("he"))
# 输出:
# True
- string.endswith(value,start,end)
判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。
参数 | 描述 |
---|---|
value | 必需。检查字符串是否以某个字符串结尾。 |
start | 可选,整数。开始检索的位置,默认是0。 |
end | 可选,整数。结束检索的位置,默认是字符串的结尾。 |
a="hello,world!"
print(a.endswith("world!"))
# 输出:
# True
4.编码、解码(string.encode()/bytes.decode())
方法 | 描述 |
---|---|
string.encode() | 以指定的编码格式编码字符串。 |
string.decode() | 以指定的解码格式解码字符串。 |
- string.encode(encoding=encoding, errors=errors)
- bytes.decode(decoding=decoding, errors=errors)
参数 | 描述 |
---|---|
encoding/decoding | 可选,字符串。规定要使用的编码/解码,默认是UTF-8。 |
errors | 可选,字符串。规定错误的方法,合法值是: 'backslashreplace’ - 使用反斜杠代替无法编码的字符。 ‘ignore’ - 忽略无法编码的字符。 ‘namereplace’ - 用解释字符的文本替换字符。 ‘strict’ - 默认值,失败时引发错误。 ‘replace’ - 用问号替换字符。 ‘xmlcharrefreplace’ - 用 xml 字符替换字符。 |
a="hello"
a_utf8=a.encode('UTF-8') #str通过encode()方法可以编码为指定的bytes
a_gbk=a.encode('GBK')
print("UTF-8 编码:", a_utf8)
print("GBK 编码:",a_gbk)
# 输出:
# UTF-8 编码: b'hello'
# GBK 编码: b'hello'
print("UTF-8 解码:",a_utf8.decode('UTF-8','strict'))
print("GBK 解码:",a_gbk.decode('GBK','strict'))
# 输出:
# UTF-8 解码: hello
# GBK 解码: hello
当从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法。反之,则使用encode()方法即可!
article_bytes=b"article.txt"
print(article_bytes,type(article_bytes))
# 输出:
# b'article.txt' <class 'bytes'>
print(article_bytes.decode("utf-8"))
# 输出:
# article.txt
参考文章:python string和bytes类型互相转换
5.填充对齐(center()/ljust()/rjust()/zfill())
- string.center(length,character)
返回一个指定的宽度居中的字符串,character为填充的字符,默认为空格。
参数 | 描述 |
---|---|
length | 必需。所返回字符串的长度。 |
character | 可选。填补两侧缺失空间的字符,默认是“”(空格)。 |
a="hello"
print(a.center(10,"*"))
# 输出:
# **hello***
- string.ljust(length,character)
返回一个原字符串左对齐并使用指定字符填充(默认为空格)至指定长度的新字符串,如果指定长度小于原字符串的长度则返回原字符串。
参数 | 描述 |
---|---|
length | 必需。所返回字符串的长度。 |
character | 可选。填补两侧缺失空间的字符,默认是“”(空格)。 |
a="hello"
print(a.ljust(10,"*"))
# 输出:
# hello*****
- string.rjust(length,character)
返回一个原字符串右对齐并使用指定字符填充(默认为空格)至长度的新字符串,如果指定长度小于原字符串的长度则返回原字符串。
参数 | 描述 |
---|---|
length | 必需。所返回字符串的长度。 |
character | 可选。填补两侧缺失空间的字符,默认是“”(空格)。 |
a="hello"
print(a.rjust(10,"*"))
# 输出:
# *****hello
- string.zfill(len)
返回指定长度的字符串,原字符串右对齐,前面填充0。
参数 | 描述 |
---|---|
len | 必需,数字。规定要删除的元素的位置。 |
a="hello"
b="welcome to my world!"
c"10.00"
print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
# 输出:
# 00000hello
# welcome to my world!
# 0000010.00
6.删除左/右指定字符(lstrip()/rstrip()/strip())
- string.lstrip(characters)
用于删除字符串左边的指定字符(默认为空格),包括空格、换行符、回车符、制表符,或字符序列。
参数 | 描述 |
---|---|
characters | 可选。一组作为前导字符要删除的字符。 |
a=",,,,,rrttgg.....hello.....world"
a.lstrip(',.grt')
# 输出:
# 'hello.....world'
- string.rstrip(characters)
用于删除字符串末尾的指定字符(默认为空格),包括空格、换行符、回车符、制表符,或字符序列。
参数 | 描述 |
---|---|
characters | 可选,一组作为结尾字符要删除的字符。 |
a=",,,,,rrttgg.....hello.....world"
a.rstrip(',.grt')
# 输出:
# ',,,,,rrttgg.....hello.....world'
a=",,,,,rrttgg.....hello.....world"
a.rstrip(',.heworld')
# 输出:
# ',,,,,rrttgg'
- string.strip(characters)
用于删除字符串头尾指定字符(默认为空格),包括空格、换行符、回车符、制表符,或字符序列。
参数 | 描述 |
---|---|
characters | 可选,一组字符。要删除的前导/尾随字符的字符。 |
a=",,,,,rrttgg.....hello.....world"
print(a.strip(',.grt'))
# 输出:
# 'hello.....world'
7.判断字符串(isspace()/isprintable()/isidentifier()/isalnum()/isalpha()/isdigit()/isnumeric()/isdecimal())
方法 | 描述 |
---|---|
string.isspace() | 检测字符串是否只由空白字符组成。 |
string.isprintable() | 检查文本中的所有字符是否可打印。 |
string.isidentifier() | 检查字符串中是否是有效标识符。 |
string.isalnum() | 检测字符串是否由字母和数字组成。 |
string.isalpha() | 检测字符串是否只由字母或文字组成。 |
string.isdigit() | 检测字符串是否只由数字组成。 |
string.isnumeric() | 检测字符串是否只由数字组成,数字可以是Unicode数字,全角数字(双字节),罗马数字,汉字数字。 |
string.isdecimal() | 检查unicode对象中的所有字符是否都是小数。 |
# string.isspace()
# 如果字符串中所有字符都是空格,isspace()方法返回True,否则返回False。
a=" hello"
print(a.isspace())
# 输出:
# False
# string.isprintable()
# 如果所有字符都是可打印,返回True,否则返回False。不可打印的字符可以是回车和换行符。
a="hello!\n how's going?"
print(a.isprintable())
# 输出:
# False
# string.isidentifier()
# 如果字符串是有效标识符,则isidentifier()方法返回True,否则返回False。
# 如果字符串包含数字字母(a-z)和(0-9)或下划线(_),则该字符串被视为有效标识符。有效标识符不能以数字开头或包含任何空格。
a="hello"
b="World!"
c="3mary"
d="thank you"
print(a.isidentifier())
# 输出:
# True
print(b.isidentifier())
# 输出:
# False
print(c.isidentifier())
# 输出:
# False
print(d.isidentifier())
# 输出:
# False
# string.isalnum()
# 检测字符串是否由字母和数字组成。
a="hello 12"
print(a.isalnum())
# 输出:
# False
# string.isalpha()
# 检测字符串是否只由字母或文字组成。
a="hello 12"
print(a.isalpha())
# 输出:
# False
# string.isdigit()
# 如果所有字符都是数字,则 isdigit() 方法将返回 True,否则返回 False。
# 指数(例如²)也被视作数字。
a = "\u0030" # unicode for 0
b = "\u00B2" # unicode for ²
print(a.isdigit())
print(b.isdigit())
# 输出:
# True
# True
# string.isnumeric()
# 如果所有字符均为数字(0-9),则 isumeric() 方法返回 True,否则返回 False。
# 指数(比如 ² 和 ¾)也被视为数字值。
a = "\u0030" # unicode for 0
b = "\u00B2" # unicode for ²
c = "10km2"
print(a.isnumeric())
print(b.isnumeric())
print(c.isnumeric())
# 输出:
# True
# True
# False
# string.isdecimal()
# 如果所有字符均为小数(0-9),则 isdecimal() 方法将返回 True。
# 此方法用于 unicode 对象。
a = "\u0030" # unicode for 0
b = "\u0047" # unicode for G
print(a.isdecimal())
print(b.isdecimal())
# 输出:
# True
# False
8.格式化字符串指定值(format())
方法 | 描述 |
---|---|
string.format() | https://blog.csdn.net/sodaloveer/article/details/134133286 |
string.format_map() | 格式化字符串中的指定值。 |
- string.format_map(mapping)
参数 | 描述 |
---|---|
mapping | 字典类型的数据。 |
a="my name is {name},I'm {age}"
dict_1={'name':'Tina','age':21}
print(a.format_map(dict_1))
# 输出:
# my name is Tina,I'm 21
9.拆分、截取(split()/rsplit()/splitlines())
- string.split(separator,max)
通过指定分隔符(默认为空白字符)从左侧对字符串进行切片成列表,如果第二个参数num有指定值,则分割为num+1个子字符串。
参数 | 描述 |
---|---|
separator | 可选。规定分割字符串时要使用的分隔符,默认为空白字符。 |
max | 可选。规定要执行的拆分数。默认值为-1,即’所有出现次数’。 |
a="hello,world"
print(a.split(','))
# 输出:
# ['hello', 'world']
b = "apple#banana#cherry#orange"
print(b.split('#'))
# 输出:
# ['apple', 'banana', 'cherry', 'orange']
b = "apple#banana#cherry#orange"
print(b.split('#',1)) #将字符串拆分为最多 2 个项目的列表
# 输出:
# ['apple', 'banana#cherry#orange']
- string.rsplit(separator, max)
通过指定分隔符(默认为空白字符)从右侧对字符串进行切片成列表,如果第二个参数num有指定值,则分割为num+1个子字符串。
参数 | 描述 |
---|---|
separator | 可选。规定分割字符串时要使用的分隔符,默认为空白。 |
max | 可选。规定要执行的拆分数。默认值为-1,即’所有出现次数’。 |
b = "apple#banana#cherry#orange"
print(b.rsplit('#',1))
# 输出:
# ['apple#banana#cherry', 'orange']
- string.splitlines(keeplinebreaks)
按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
参数 | 描述 |
---|---|
keeplinebreaks | 可选。规定是否应包含换行符(True)或不包含(False)。默认值不包含(False)。 |
a="Thank you.\nLooking forward to you."
print(a.splitlines())
# 输出:
# ['Thank you.', 'Looking forward to you.']
a="Thank you.\nLooking forward to you."
print(a.splitlines(True))
# 输出:
# ['Thank you.\n', 'Looking forward to you.']
10.拆分字符串,返回元组(partition()/rpartition())
方法 | 描述 |
---|---|
string.partition() | 搜索指定的字符串,并将该字符串拆分为包含三个元素的元组。第一个元素包含指定字符串之前的部分,第二个元素包含指定字符串,第三个元素包含字符串后面的部分。 |
string.rpartition() | 搜索指定字符串的最后一次出现,并将该字符串拆分为包含三个元素的元组。第一个元素包含指定字符串之前的部分,第二个元素包含指定字符串,第三个元素包含字符串之后的部分。 |
- string.partition(value)
此方法搜索指定字符串的第一个匹配项。并将该字符串拆分为包含三个元素的元组。第一个元素包含指定字符串之前的部分,第二个元素包含指定字符串,第三个元素包含字符串后面的部分。
参数 | 描述 |
---|---|
value | 必需。要检索的字符串。 |
a="sodagreen come back!!!"
print(a.partition("come"))
# 输出:
# 1 - “匹配”之前的所有内容
# 2 - “匹配”
# 3 - “匹配”之后的所有内容
# ('sodagreen ', 'come', ' back!!!')
#如果找不到指定的值,则 partition() 方法将返回一个元组,其中包含:1 - 整个字符串,2 - 空字符串,3 - 空字符串:
a="sodagreen come back!!!"
print(a.partition("welcome"))
# 输出:
# ('sodagreen come back!!!', '', '')
- string.rpartition(value)
搜索指定字符串的最后一次出现。并将该字符串拆分为包含三个元素的元组。第一个元素包含指定字符串之前的部分,第二个元素包含指定字符串,第三个元素包含字符串之后的部分。
参数 | 描述 |
---|---|
value | 必需。要检索的字符串。 |
a="oh,oh,oh,sodagreen come back!!!"
print(a.rpartition("oh"))
# 输出:
# 1 - “匹配”之前的所有内容
# 2 - “匹配”
# 3 - “匹配”之后的所有内容
# ('oh,oh,', 'oh', ',sodagreen come back!!!')
# 如果找不到指定的值,则 rpartition() 方法将返回一个元组,其中包含:1 - 整个字符串,2 - 一个空字符串,3 - 一个空字符串:
a="oh,oh,oh,sodagreen come back!!!"
print(a.rpartition("in"))
# 输出:
# ('', '', 'oh,oh,oh,sodagreen come back!!!')
11.字符串转换(maketrans()/translate())
方法 | 描述 |
---|---|
maketrans() | 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 |
translate() | 返回被转换的字符串。 |
- string.maketrans(x[,y[,z]])
参数 | 描述 |
---|---|
x | 必需。字符串中要替代的字符组成的字符串。 |
y | 可选。相应的映射字符的字符串。 |
z | 可选。要删除的字符。 |
a="hello"
b=a.maketrans("e","E")
print(a.translate(b))
# 输出:
# hEllo
a="abcde"
b="12345"
trans=str.maketrans(a,b)
str1="sodagreen come back!!!"
print(str1.translate(trans))
# 输出:
# so41gr55n 3om5 213k!!!
a="abcde"
b="12345"
c="zZ"
trans=str.maketrans(a,b,c)
str1="sodagreen come back!!! Z"
print(str1.translate(trans))
# 输出:
# so41gr55n 3om5 213k!!!
12.连接(join())
- string.join(iterable)
用于序列中的元素以指定的字符连接生成一个新的字符串。
参数 | 描述 |
---|---|
iterable | 必需。所有返回值均为字符串的任何可迭代对象。 |
# 使用空格作为分隔符,将元组中的所有项目连接到字符串中。
tuple1=("sodagreen","come","back")
print(" ".join(tuple1))
# 输出:
# sodagreen come back
# 使用单词“TEST”作为分隔符,将字典中的所有项目连接成一个字符串。
dict_1 = {"name": "sodagreen", "address": "GZ"}
print("TEST".join(dict_1))
# 输出:
# nameTESTaddress
13.字符串替换(replace())
- string.replace(oldvalue,newvalue,count)
把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换不超过max次。
参数 | 描述 |
---|---|
oldvalue | 必需。要检索的字符串。 |
newvalue | 必需。替换旧值的字符串。 |
count | 可选,数字。指定要替换的旧值出现次数,默认为所有的出现。 |
a="good news!sodagreen comes back!"
a.replace("good","great")
# 输出:
# 'great news!sodagreen comes back!'
a="oh,oh,oh,good news!sodagreen comes back!"
a.replace("oh","good")
# 输出:
# 'good,good,good,good news!sodagreen comes back!'
a="oh,oh,oh,good news!sodagreen comes back!"
a.replace("oh","good",2)
# 输出:
# 'good,good,oh,good news!sodagreen comes back!'
14.Tab转换(exandtabs())
- string.exandtabs(tabsize)
将字符串中的tab符号\t替换成空格,tab符号\t默认的空格数是8,在第0,8,16,…等处给出制表符位置,如果当前位置到开始位置或上一个制表符位置的字符数不足8的倍数则以空格代替。
参数 | 描述 |
---|---|
tabsize | 可选。规定制表符大小的数字。默认的 tabsize 是 8。 |
txt = "H\te\tl\tl\to"
print(txt.expandtabs())
print(txt.expandtabs(2))
print(txt.expandtabs(4))
print(txt.expandtabs(8))
# 输出:
# H e l l o
# H e l l o
# H e l l o
# H e l l o