gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:56 25 4
gpt4 key购买 nike

我想在 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

最佳答案

使用 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']

关于python - 如何在python中替换列表中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29382120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com