Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing special character from string in python

Tags:

python

I am trying to remove a '-' character from a string using the two lines below, but it still returns the original string. If I execute the bottom two lines, it works, sha and sha2 are both strings. Any ideas?

sha = hash_dir(filepath) # returns an alpha-numeric string

print sha.join(c for c in sha if c.isalnum())

sha2 = "-7023680626988888157"

print sha2.join(c for c in sha2 if c.isalnum())
like image 399
iheartcpp Avatar asked Dec 29 '25 13:12

iheartcpp


2 Answers

python strings are immutable -- .join won't change the string, it'll create a new string (which is what you are seeing printed).

You need to actually rebind the result to the name in order for it to look like the string changed in the local namespace:

sha2 = ''.join(c for c in sha2 if c.isalnum())

Also note that in the expression x.join(...), x is the thing which gets inserted between each item in the iterable passed to join. In this case, you don't want to insert anything extra between your characters, so x should be the empty string (as I've used above).

like image 195
mgilson Avatar answered Dec 31 '25 05:12

mgilson


Did you mean:

print ''.join(c for c in sha2 if c.isalnum())
like image 22
scope Avatar answered Dec 31 '25 06:12

scope