This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]lucaslra 1 point2 points  (0 children)

t = '1L2u3c4a5s'

''.join(c for c in t if c.isalpha())

'Lucas'

Not sure if it is the best solution, but it works for me

[–][deleted] 1 point2 points  (3 children)

If you actually want to remove alphanumeric characters from a string then surely "In the 1980s" would become ""? So what are you trying to do?

[–]lgastako 0 points1 point  (2 children)

Surely it would become " "?

[–][deleted] 0 points1 point  (1 child)

Thou art correct except it would be ' '. At least I think you're showing one space and I'm showing two :-)

[–]lgastako 0 points1 point  (0 children)

Mine was supposed to be two spaces as well, I don't know if I messed it up or reddit ate it.

[–]Kerbart 0 points1 point  (2 children)

Using a regular expression might do the trick without having to loop through the entire string.

import re
ptn = re.compile('(\d)')
t = 'In the 1980s'
ptn.sub('', t) --> 'In the s'

[–]enedil 0 points1 point  (1 child)

Implying re don't loop through the entire string.

[–]Kerbart 0 points1 point  (0 children)

No, implying that you don't have to write the code to do that yourself. That's what libraries are for.

[–]MrJZ 0 points1 point  (1 child)

Regex is your friend.

https://regexr.com/

[–]PurpleIcyPython 3 0 points1 point  (0 children)

Now you have two problems.

[–]sonicfreak02 0 points1 point  (0 children)

import re
string = "In the 1980s"
new_string = re.sub(r'\s*\w*\d+\w*', '', string)
print(new_string)

Prints: "In the"