0

feeling stupid with this one :/

I know I'm using the method wrong in some way, but with only https://docs.python.org/3/library/stdtypes.html#str.replace to work with I just can't see why I can't do what I'm trying to achieve here (which I hope is obvious enough?)

import string

word2 = 'abc?ef,hi.!l@'

for x in string.punctuation:
    if x in word2:
        word2.replace(x,'')

print (word2)

I've tried a few debugs & print statements so I know it's iterating through string.substring OK, and I know it's going through word2 and recognising when each x is present, but why isn't replace() actually doing anything here?

Thanks

2 Answers 2

1

You can use str.join and comprehension to do this in one straightforward line.

import string

word2 = "abc?ef,hi.!1@"
word2 = ''.join(c for c in word2 if c not in punctuation)
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

import string

word2 = "abc?ef,hi.!l@"

for x in string.punctuation:
    if x in word2:      //works with or without
        word2 = word2.replace(x,"")// save the after replace is done.
print(word2)

output:

abcefhil

4 Comments

I might add that you don't really need the conditional if x is in word2
@juanpa.arrivillaga yea true
Thanks. It was actually the fact you have to assign to a variable what replace() produces that I was missing/didn't understand. @juanpa.arrivillaga Wow, didn't realise that either but seems obvious now. Thanks.
@Phlebas_The_Seabass you welcome, you can accept the accept the answer if it was helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.