删除除空格和数字以外的所有特殊字符并输出列表(Python)?

2024-05-29 03:03:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根像这样的绳子:

rawanswers = ["?\\n', 'WiFi\\n', 'Waf\\xef\\xac\\x82e House\\n', 'Wind\\n', ' \\n']"]

我想删除所有特殊字符(\n、问号和反斜杠),但保留空格、数字和单引号。但是在每对单引号之间,我希望删除反斜杠之后的任何内容,直到遇到空格(然后它将重新启动)。然后,我希望在每对单引号之间产生的字符串放入一个新的列表中。换句话说,我希望这是输出:

^{pr2}$

我还想在多个不同的字符串上运行相同的代码来完成相同的任务。最有效的方法是什么?在


Tags: 字符串wifihousewind空格waf斜杠绳子
3条回答

我只能想到完全删除由@或%%这样的字符串组成的符号的代码,而不是一个#或fed//n

words=['?','@a','a']
x=-1
while x<(len(words)-1):
  x=x+1
  if not words[x].isalnum():
    words.remove(words[x])
print(*words)

另外,在你的代码中你以“?,但不要以“你以a结尾”。这将导致代码错误。在

我可以想出一个简单的方法,分为两部分

import re

for string in rawanswers:
    string = re.sub(r'\\.','', string)  # Remove all \n \t etc..
    string = re.sub(r'[^\w\s]*','', string)  # Remove anything not a digit, letter, or space

如果您不希望像示例中那样使用数字,可以在第二行中将regex更改为[A-Za-z]

rawanswers中的第一项不是以单引号开头的,所以我在代码示例中添加了它。在

rawanswers = ["'?\\n', 'WiFi\\n', 'Waf\\xef\\xac\\x82e House\\n', 'Wind\\n', ' \\n'"]

#Get first list item, strip off double quotes, split on commas. 
rawanswer = rawanswers[0].strip('"').split(',')

newList = []
for item in rawanswer:
    #Strip leading space, strip single quotes, split words.
    newStr = item.lstrip().strip("'").split()
    newItem = []
    for word in newStr:
        #Remove ?, split on '\\', get first list item and assume remainder is not wanted. 
        newWord = word.replace('?','').split('\\')[0]
        if newWord: newItem.append(newWord)  

    if newItem:
        newStr =  ' '.join(newItem)
        newList.append(newStr)

print newList 

相关问题 更多 >

    热门问题