一、replace()
- 语法 :string.replace( old, new, count )
- 参数:
old :(必选)被替换的字符串
new :(必选)替换后的字符串
count :(可选,整型)替换的次数 - 实例:
Str1 = '"hello world "hello hello"' # 双引号
str1 = Str1.replace('"','')
Str2 = "hello'morning'world" # 单引号
str2 = Str2.replace("'",'')
LIST = ['hello','"I love you"','world'] # 列表1
List = [str3.replace('"','') for str3 in LIST]
LIST = ['hello','"I love you"','world'] # 列表2
new_list = []
for a in LIST:
a = a.replace('"',"")
new_list.append(a)
LIST = ['hello','"I love you"','world'] # 列表3
for a in range(len(LIST)):
LIST[a] = LIST[a].replace('"','')
- 返回的结果:
‘hello world hello hello’
‘hellomorningworld’
[‘hello’, ‘I love you’, ‘world’] - 替换次数为「正数」时,按照从左到右的顺序替换,设置几次就替换几次
替换次数为「负数」时,无论负几,都会替换所有匹配到的内容
二、join()方法
- ==作用:==移除字符串中所有引号
- 实例
Str = '"hello world "hello hello"'
''.join(i for i in Str if i not in '"')
- 语法: ‘sep’.join(seq)。 sep:分隔符。可以为空
三、strip()方法,只针对双引号
- strip()
代码如下(示例):
Str = '"hello world "hello hello"'
str = Str.strip('"')
输出:‘hello world "hello hello’,只将左右两端的引号删除,中间的不删除
2. lstrip()
代码如下(示例):
Str = '"hello world "hello hello"'
str = Str.lstrip('"')
输出: ‘hello world “hello hello”’,将最左边的双引号删除
3. rstrip()
代码如下(示例):
Str = '"hello world "hello hello"'
str = Str.rstrip('"')
输出:‘"hello world "hello hello’,将最右边的双引号删除