简体   繁体   English

如何在python中替换列表中的字符

[英]how to replace the characters of the list in python

I want to write a code in python that will replace every every small letter character with "a" , every capital letter with "A" and every digit with 0. I write code but it caused an error of x not in list , code is below 我想在python中编写一个代码,将每个小字母字符都替换为“ a”,将每个大写字母替换为“ A”,将每个数字替换为0。我编写代码,但是它导致x不在列表中的错误,代码是下面

tokens = ["apple","banana","Orange", "pineApple", "10nuts"]
for token in tokens:
    for ch in token:
        if ch.islower():
            loc = tokens.index(ch)
            tokens.remove(ch)
            tokens.insert(loc,'a');
        elif ch.isupper():
            loc = tokens.index(ch)
            tokens.remove(ch)
            tokens.insert(loc,'A');
        elif ch.isdigit():
            loc = tokens.index(ch)
            tokens.remove(ch)
            tokens.insert(loc,'0');
for t in tokens:
    print t

Using regular expressions : 使用正则表达式

from re import sub

tokens = ["apple","banana","Orange", "pineApple", "10nuts"]

for i, token in enumerate(tokens):
    token = sub(r'[A-Z]', 'A', token)
    token = sub(r'[a-z]', 'a', token)
    token = sub(r'\d', '0', token)
    tokens[i] = token

print tokens
## Output: ['aaaaa', 'aaaaaa', 'Aaaaaa', 'aaaaAaaaa', '00aaaa']

You should use regular expressions to perform this task: 您应该使用正则表达式执行此任务:

import re

tokens = ["apple","banana","Orange", "pineApple", "10nuts"]

upper = re.compile(r"[A-Z]")
lower = re.compile(r"[a-z]")
number = re.compile(r"[0-9]")

for token in tokens:
    token = re.sub(upper,'A',token)
    token = re.sub(lower,'a',token)
    token = re.sub(number,'0',token)
    print token

The variables upper, lower and number are precompiled regular expressions, since you are using them in a loop, this is faster. 变量upper,lower和number是预编译的正则表达式,因为您在循环中使用它们,因此速度更快。

You could also shorten down the loop to one three lines: 您还可以将循环缩短到三行:

for token in tokens:
    token = re.sub(upper,'A',re.sub(lower,'a',re.sub(number,'0',token)))
    print token

Hope this helps 希望这可以帮助

EDIT: Took my code from above, with the one-liner, but used the enumeration loop as suggested by pzp1997: 编辑:用单线从上面拿了我的代码,但是使用了pzp1997建议的枚举循环:

import re

tokens = ["apple","banana","Orange", "pineApple", "10nuts"]

upper = re.compile(r"[A-Z]")
lower = re.compile(r"[a-z]")
number = re.compile(r"[0-9]")

for i, token in enumerate(tokens):
    tokens[i] = re.sub(upper,'A',re.sub(lower,'a',re.sub(number,'0',token)))

print tokens

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

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