3

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

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that was the problem.
5

Did you mean:

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

Comments

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.