简体   繁体   English

从 Python 中的字符串列表中删除特殊字符?

[英]Removing especial characters from a string list in Python?

I have two lists;我有两个清单; the first a string list with names ( name_list ) in it and a second list with especial characters ( char_list ).第一个带有名称( name_list )的字符串列表和带有特殊字符( char_list )的第二个列表。 What I'm looking for to do is to remove all the especial characters that are found in any placement of each letter in each name from the name_list .我正在寻找做的是从name_list中删除在每个名称中每个字母的任何位置中找到的所有特殊字符。

Psdt. psdt。 I know that there are other ways to do so (like using reg) but in this case I'm attempting to do it without using such especial functions/libraries, just.replace() at much like I've been trying shown below:我知道还有其他方法可以做到这一点(比如使用 reg),但在这种情况下,我试图在不使用此类特殊函数/库的情况下做到这一点,just.replace() 就像我一直在尝试的如下所示:

Say this is my full especial characters list:假设这是我的完整特殊字符列表:

char_list = ['%',']','(','/','&','?','¨','+']

Those characters above are the ones that I'm looking for to replace in the name_list , say these are the names:上面的那些字符是我要在name_list中替换的字符,比如说这些是名称:

name_list = ['LAURE]N', 'NIC%HOL/AS', 'nichol?as', '(Vic(t¨oria', 'H+AROLD']

And this is my attempt using loops and conditionals but I still haven't got it quite right:这是我使用循环和条件的尝试,但我仍然没有完全正确:

for index, value in enumerate(name_list):
 
  if char_list[index + 1] in value:
    name_list[index + 1].lower().replace(char_list[index + 1], "")
  
  print(set(name_list))

I'm printing set(name_list) and including .lower() because besides removing/replacing the chars I'm also trying to retrieve the unique names from the name_list我正在打印set(name_list)并包括.lower()因为除了删除/替换字符之外,我还试图从name_list中检索唯一名称

This is of course giving me an error because I haven't figured out yet so any help to do it properly this way or very close without other libraries is very well received: :)这当然给了我一个错误,因为我还没有弄清楚,所以任何帮助以这种方式正确完成或在没有其他库的情况下非常接近的帮助都非常受欢迎::)

You don't have to do the in check.您不必in检查。 Just do the replaces.只做替换。

char_list = '%](/&?¨+'
name_list = ['LAURE]N', 'NIC%HOL/AS', 'nichol?as', '(Vic(t¨oria', 'H+AROLD']
new_list = []
for n in name_list:
    for c in char_list:
        n = n.replace(c,'')
    new_list.append(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM