将字符串两端或中间的引号(单/双)删除


一、replace()

  1. 语法 :string.replace( old, new, count )
  2. 参数
    old :(必选)被替换的字符串
    new :(必选)替换后的字符串
    count :(可选,整型)替换的次数
  3. 实例:
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('"','')
  1. 返回的结果:
    ‘hello world hello hello’
    ‘hellomorningworld’
    [‘hello’, ‘I love you’, ‘world’]
  2. 替换次数为「正数」时,按照从左到右的顺序替换,设置几次就替换几次
    替换次数为「负数」时,无论负几,都会替换所有匹配到的内容

二、join()方法

  1. ==作用:==移除字符串中所有引号
  2. 实例
Str = '"hello world "hello hello"'
''.join(i for i in Str if i not in '"')
  1. 语法: ‘sep’.join(seq)。 sep:分隔符。可以为空

三、strip()方法,只针对双引号

  1. 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’,将最右边的双引号删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值