gpt4 book ai didi

python - 删除子字符串时出现问题

转载 作者:行者123 更新时间:2023-12-03 18:44:08 24 4
gpt4 key购买 nike

所以我试图从用户输入中删除子字符串(数字和特殊字符),然后反转整个输入字符串。数字删除工作正常,但特殊字符没有。请看一下。

en_word = input()
x = 0
y = 0
f_character = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "@", "$", "%", "^", "&", "*", "(",
")", "-"]
while f_character[x] in en_word:
en_word = en_word.replace(f_character[x], "")
x += 1
print(en_word[:: -1])

输入
123o%l$leh321

预期产出
hello

实际产量
hel$l%o 

最佳答案

只要字母不在单词中,您的 while 循环就会退出 - '4' 就是这种情况 - 所有其他的都不会被检查。
使固定:

en_word = "123o%l$leh321" 
y = 0
f_character = ["1", "2", "3", "4", "5", "6", "7", "8", "9",
"!", "@", "$", "%", "^", "&", "*", "(", ")", "-"]
for c in f_character:
en_word = en_word.replace(c, "")
print(en_word[:: -1])

有一个更好的方法来做到这一点,使用 str.translatestr.maketrans :
replacer = str.maketrans("", "", "123456789!@$%^&*()-")
en_word = "123o%l$leh321"

print(en_word.translate(replacer)[::-1]) # hello
Doku str.maketrans :

This static method returns a translation table usable for str.translate.

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

关于python - 删除子字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61373528/

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