【问题标题】:how to remove first and last character of a string if it is special character using regex in python [closed]如果在python中使用正则表达式是特殊字符,如何删除字符串的第一个和最后一个字符[关闭]
【发布时间】:2018-08-11 15:36:03
【问题描述】:

我有一个类似的列表,

mylist=["'one'","{two}","'three'","four","{{{five}}}","s*ix"]

对于每个元素,如果它是特殊字符(a-z 除外),我想删除第一个和最后一个字符。

我想要的输出是,

 out_list=["one","two","three","four","{{five}}","s*ix"]

【问题讨论】:

  • 您需要定义什么是特殊的。还有其他你不想要的角色吗?
  • 我编辑了我的问题

标签: python regex string list


【解决方案1】:

你可以试试这个:

import re
mylist=["'one'","{two}","'three'","four","{{{five}}}","s*ix"] 
new_list = list(map(lambda x:re.sub('^[^a-z]|[^a-z]$', '', x), mylist))

输出:

['one', 'two', 'three', 'four', '{{five}}', 's*ix']

编辑:要删除包含特殊字符的元素,你可以试试这个:

new_list = list(filter(lambda x:not re.findall('^[^a-z]|[^a-z]$', x), mylist))

输出:

['four', 's*ix']

【讨论】:

  • 我的原始数据不仅包含这两个特殊字符,我想删除任何类型的特殊字符
  • 特殊字符是指非字母吗?
  • @pyd 你能澄清一下在这个问题的范围内什么是特殊字符吗?
  • 除了 {a-z}
  • @pyd 请查看我最近的编辑。
【解决方案2】:

r'[^a-zA-Z0-9]' 这是除数字和字母之外的所有内容,re.sub 删除这些。您可以使用 \char 在正则表达式中添加您希望允许的任何其他字符。

import re

mylist=["'one'","{two}","'three'","four","{{{five}}}"]

x = [re.sub(r'[^a-zA-Z0-9]', '', i) for i in mylist]

print(x)

【讨论】:

    【解决方案3】:

    你可以试试这个:

    mylist=["'one'","{two}","'three'","four","{{{five}}}"]
    newlist=[]
    for e in mylist:
        if e[0] not in "qwertyuiopasdfghjklzxcvbnm":
            newlist.append(e[1:-1])
    

    或更短:

    [e[1:-1] if e[0] not in "qwertyuiopasdfghjklzxcvbnm" else e for e in mylist]
    

    【讨论】:

      【解决方案4】:

      制作翻译表,将不需要的字符翻译成空字符串

      import string, operator
      table = str.maketrans({c:'' for c in string.punctuation})
      a = ["'one'","{two}","'three'","four","{{{five}}}","s*ix"]
      

      翻译第一个和最后一个字符,并重构。

      #helpers for readability
      first = operator.itemgetter(0)
      last = operator.itemgetter(-1)
      middle = slice(1,-1)
      for thing in a:
          beginning = first(thing).translate(table)
          mid = thing[middle]
          end = last(thing).translate(table)
          print(''.join([beginning, mid, end]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-05
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多