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?
-
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 Py3John Machin– John Machin2017年02月08日 06:38:37 +00:00Commented Feb 8, 2017 at 6:38
-
@johnmachin will do, sorry about thatbyu– byu2017年02月09日 01:13:16 +00:00Commented Feb 9, 2017 at 1:13
3 Answers 3
You can use string.translate
:
s = "IslkdoIoooI"
import string
s.translate(string.maketrans("Io", "10"))
# '1slkd010001'
answered Feb 8, 2017 at 2:13
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
-
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. Youri
is a character; calling itc
would be better.John Machin– John Machin2017年02月08日 06:55:34 +00:00Commented Feb 8, 2017 at 6:55
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
lang-py