So im trying to remove a substrings (numbers and special characters) from the user input and then reverse the whole input string. The number removing works fine, however the special charachter does not. Please take a look.
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])
Input
123o%l$leh321
Expected Output
hello
Actual Output
hel$l%o
Your while loop will exit as soon as a letter is not inside the word - this is the case for '4'
-all others will not be checked.
Fix:
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])
There is a better way to do this, using str.translate and str.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With