0
PUNCTUATION = '''!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'''

WHITE_SPACE = ' \t\n\r\v\f'

EXTRANEOUS  = PUNCTUATION + WHITE_SPACE

str = ["HeLlo!!!,","H%I"]
l = []
for s in str:
    for x in EXTRANEOUS:
        sd = s.replace(x,"")
    l.append(sd)
print(l)

Hi! My python code is not working for some reason. I'm trying to get rid of any punctuation mark and white space.

5 Answers 5

2

Your code wipes out the result of previous replacements.

for s in str:
    for x in EXTRANEOUS:
        s = s.replace(x,"")
    l.append(s)
Sign up to request clarification or add additional context in comments.

Comments

1

Just use re.sub:

import re
str = ["HeLlo!!!,","H%I"]
final_str = [re.sub('\W+', '', i) for i in str]

Output:

['HeLlo', 'HI']

Comments

0

You always use the unmodified version s of your strings. Just replace sd with s:

PUNCTUATION = '''!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'''

WHITE_SPACE = ' \t\n\r\v\f'

EXTRANEOUS  = PUNCTUATION + WHITE_SPACE

str = ["HeLlo!!!,","H%I"]
l = []
for s in str:
    for x in EXTRANEOUS:
        s = s.replace(x,"")
    l.append(s)
print(l)

Comments

0

You can do it like this:

PUNCTUATION = '''!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'''
WHITE_SPACE = ' \t\n\r\v\f'    
EXTRANEOUS = PUNCTUATION + WHITE_SPACE    
str_list = ["HeLlo!!!","H%I"] # this a list
result = []

for s in str_list:
    l = ""
    for x in s:
        if x not in EXTRANEOUS:
            l += x
    result.append(l)

print(result)

Output:

['HeLlo', 'HI']

Comments

0

As others have said, you are not storing the output of the replace() function in s. Just replace sd = s.replace(x,"") with s = s.replace(x,"") and l.append(s). One more way to remove punctuation is to do like this .

Python 2.x:

import string

stri = ["HeLlo!!!,","H%I"]
l = []
for s in stri:
    l.append(s.translate(None, string.punctuation))
print(l)

Python 3.x

import string

stri = ["HeLlo!!!,","H%I"]
l = []
for s in stri:
    l.append(s.translate(str.maketrans("","", string.punctuation)))
print(l)

Output:

['HeLlo', 'HI']

Comments

Your Answer

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