0

In my code, I need to replace all Is with 1s, and all os with 0s. I can do it in two statements, which is code as follows:

stringtochange=raw_input("What do you want to change?")
print stringtochange.replace("I","1")
print stringtochange.replace("o","0")

but I need it to do it all in one fell swoop. Any ideas?

asked Feb 8, 2017 at 2:08
2
  • Please edit your question to include a Python2.x or Python3.x tag -- the args for str.translate have changed a lot between Py2 and Py3 Commented Feb 8, 2017 at 6:38
  • @johnmachin will do, sorry about that Commented Feb 9, 2017 at 1:13

3 Answers 3

3

You can use string.translate:

s = "IslkdoIoooI"
import string
s.translate(string.maketrans("Io", "10"))
# '1slkd010001'
answered Feb 8, 2017 at 2:13
0

You can map multiple values using list comprehension:

str = "Itesto"
source = ['I', 'o']
dest = ['1', '0']
''.join([dest[source.index(i)] if i in source else i for i in str])
>> '1test0'
answered Feb 8, 2017 at 2:22
1
  • Good answer -- Some remarks on style etc: Don't use the name str for your own objects -- it masks out the built-in type. Also it's OK to use one-letter names provided their scope is not very wide; however i (and j and k) signify "index" to most people. Your i is a character; calling it c would be better. Commented Feb 8, 2017 at 6:55
0

This alternative uses a dict to map source characters to replacement characters:

>>> s = "HIJnop"; xmap = {"I": "1", "o": "0"}; ''.join([xmap.get(c, c) for c in s])
'H1Jn0p'
answered Feb 8, 2017 at 6:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.