-3

i have string, for example: '1212kk , l ' With a regex I have to strip out everything except numbers and letters and get this: '1212kkl'

1 Answers1

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