更改子列表中的字符 [英] Change Character in Sublist

查看:47
本文介绍了更改子列表中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道这是一个非常愚蠢的问题.我试图查找答案,但我几乎不知道该问些什么. (抱歉,标题有点模糊).但是,我走了.我有一个词表.我想摆脱该列表中的不良字符.

I already know this is a really dumb question. I tried looking up my answer but I barely know what to ask. (sorry if the title is a little vague). But Here I go. I have a list of words. I'm wanting to get rid of the bad characters in that list.

List = ["I?", "Can", "!Not", "Do.", "It"]
BadChars = ["?", "!", "."]

for word in List:
    for char in word:
        if char in BadChars:
            char = ""

print(List)

同样,我知道这很简单,但是我无法弄清楚.原谅我.

Again, I know this is very simple, but I just can't figure it out. Forgive me.

顺便说一句,这没有给我一个错误.只是返回了未更改的列表.

Btw, it's not giving me an error. It's just returning the List untouched.

推荐答案

对于每个单词的每个字符,您可以使用replace方法:

You could use the replace method, for each char for each word:

List = ["I?", "Can", "!Not", "Do.", "It"]
BadChars = ["?", "!", "."]

for i in range(len(List)):
  for char in BadChars:
    List[i] = List[i].replace(char, "")

print(List) # ==> ['I', 'Can', 'Not', 'Do', 'It']

也可以使用正则表达式:

A regex may be used as well:

import re

List = ["I?", "Can", "!Not", "Do.", "It"]
BadChars = ["?", "!", "."]
rgx = '[%s]'%(''.join(BadChars))

List = [re.sub(rgx, "", word) for word in List]

print(List) # ==> ['I', 'Can', 'Not', 'Do', 'It']

这篇关于更改子列表中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆