我想在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
答案 0 :(得分:2)
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']
答案 1 :(得分:1)
您应该使用正则表达式来执行此任务:
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
变量upper,lower和number是预编译的正则表达式,因为你在循环中使用它们,这样会更快。
您还可以将循环缩短为三行:
for token in tokens:
token = re.sub(upper,'A',re.sub(lower,'a',re.sub(number,'0',token)))
print token
希望这有帮助
编辑:使用单行代码从上面取代我的代码,但是使用了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