一、替换:replace()
replace()参数:
①:__old:指需要替换的字符
②:__new:指新的字符
③:__count:指替换的次数
替换方式:
1、位置实参传入参数:__old—第一位,__new—第二位,__count—第三位。
old_str = " My name is a string, My nickname is str "
new_str = old_str.replace('My', 'You', 1)
print(new_str)
2、指定关键字参数进行传参:
old_str = " My name is a string, My nickname is str "
new_str = old_str.replace(__old='My', __new='You', __count=2)
print(new_str)
注意:位置参数跟在关键字参数后面,不然会报错哦
二、分隔:split()
split()参数
①:sep:分隔的条件,默认为空格。
②:maxsplit:分隔的次数,表示没有限制。
分隔方式:
1.位置实参传入参数
old_str = " My name is a string, My nickname is str "
list_str = old_str.split('s', 2)
print(list_str)
2.指定关键字参数进行传参:
old_str = " My name is a string, My nickname is str "
list_str = old_str.split(sep='a', maxsplit=3)
print(list_str)
三、针对字符串首尾部的删除空白 strip()
string.strip()返回一个删除了前导和尾部空白的字符串副本。如果给定了chars而不是None,请删除chars中的字符。
old_str = " My name is a string, My nickname is str "
new_str = old_str.strip()
print(new_str)
old_str = " My name is a string, My nickname is str "
new_str = old_str.strip()
print(new_str)
print(new_str.strip('My'))
注意:strip()不接受关键字传参,我试过了.....
四、合并 join()
如下指定合并的条件为空格,也可以指定其他的内容为合并的条件哦
1.合并只含有字符为元素的列表与元组为新字符串
list_str = ['My', 'name', 'is', 'a', 'string', 'My', 'nickname', 'is', 'str']
tuple_str = ('My', 'name', 'is', 'a', 'string', 'My', 'nickname', 'is', 'str')
str1 = ' '.join(list_str )
str2 = ' '.join(tuple_str)
print(str1)
print(str2)
2、合并只含有字符为元素集合为新字符串
set_str = {'My', 'name', 'is', 'a', 'string', 'My', 'nickname', 'is', 'str'}
str1 = ' '.join(set_str)
print(str1)
注意:里面的元素合并为新的字符串的时候,顺序是乱序的哦 每次执行的结果都不相同
3.合并所有的键都为字符的字典为新字符串
dict_str = {
'1': 'My', '2': 'name', '3': 'is', '4': 'a', '5': 'string', '6': 'My', '7': 'nickname', '8': 'is', '9': 'str'
}
str1 = ' '.join(dict_str)
print(str1)
注意:这里合并的内容是字典的键哦