i have string, for example: '1212kk , l ' With a regex I have to strip out everything except numbers and letters and get this: '1212kkl'
Asked
Active
Viewed 362 times
-3
-
@Dschoni Then what do you think `re.sub` is doing? – superb rain Aug 27 '20 at 13:34
-
Does this answer your question? [How to input a regex in string.replace?](https://stackoverflow.com/questions/5658369/how-to-input-a-regex-in-string-replace) – Dschoni Aug 27 '20 at 13:35
-
Sorry, that was too fast ;) – Dschoni Aug 27 '20 at 13:35
-
2Give me regex for X is not a valid question. Please read [ask] and [edit] what you tried into you question – Patrick Artner Aug 27 '20 at 13:43
-
`re.sub('[\W_]+', '', str)` – ctwheels Aug 27 '20 at 14:00
1 Answers
1
Use the str.isalnum()
which chekcs if its either letter or digit:
text = "1212kk , l"
# Option 1:
# The `x for x in text` goes on string characters
# The `if x.isalnum()` filters in only letters and digits
# The `''.join()` takes the filtered list and joins it to a string
filtered = ''.join([x for x in text if x.isalnum()])
# Option 2:
# Applay `filter` of `text` characters that `str.isalnum` returns `True` for them
# The `''.join()` takes the filtered list and joins it to a string
filtered = ''.join(filter(str.isalnum, text))
# 1212kkl
print(filtered )

Aviv Yaniv
- 6,188
- 3
- 7
- 22