Reputation: 3163
I am trying to remove certain characters from a string. My way of going about it is to turn the string into a list, iterate through each list and append each good character to a new list and return that new list but for some reason, it doesn't do that. This is the input:
"4193 with words"
and this is the output:
4193withwords
In other words, the only part of the code which works is the part of removing the whitespaces. Here is my entire code:
class Solution:
def myAtoi(self, str: str) -> int:
illegal_char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', '#', '$', '%', '^', '&' '*', '(', ')', '=', '+', '[', ']', '{', '}', '|']
new_list = []
integer_list = list(str)
for i in range(len(integer_list)):
if integer_list[i] != any(illegal_char):
new_list.append(integer_list[i])
output = ''.join(new_list)
output = output.replace(' ', '')
return output
Upvotes: 1
Views: 34
Reputation: 45
Hmm, this is a very complicated way of replacing some characters. I suggest you, to learn some regex, as it could help you alot. There is a regex library for python called re.
This would be my solution:
import re
mytext = "4193 with words"
newtext = re.sub("\s", "", mytext)
Upvotes: 1
Reputation: 26039
You can do a join
on a list-comprehension. What you need is a membership check in list and form string with only those characters you need:
''.join([x for x in s if x not in illegal_char]).replace(' ', '')
Note that I have renamed your string to s
, because str
is a built-in.
Also to add, if you can include space as illegal_char
you can avoid replace
at the end.
Upvotes: 2