user8782165
user8782165

Reputation:

Python: replace function not working

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.

Upvotes: 0

Views: 97

Answers (5)

Miraj50
Miraj50

Reputation: 4407

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']

Upvotes: 0

utengr
utengr

Reputation: 3345

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']

Upvotes: 0

Daniel
Daniel

Reputation: 42748

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)

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Your code wipes out the result of previous replacements.

for s in str:
    for x in EXTRANEOUS:
        s = s.replace(x,"")
    l.append(s)

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

Just use re.sub:

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

Output:

['HeLlo', 'HI']

Upvotes: 1

Related Questions