简体   繁体   中英

Removing special character from string in 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())

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).

你的意思是:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM