'Keeping punctuation in string while getting dictionary values
I have the below code and looking to get abc, cde
as output. I have tried to convert the None
s to empty strings using str(i or ' ') for i in m
and got abc cde
as output. Is it possible to isolate the comma ,
such that the output would be abc, cde
?
d = {'1':'a', '2':'b', '3':'c', '4':'d', '5':'e'}
s = '123, 345'
m = [d.get(i) for i in s]
print(''.join(map(str, m)))
# output -> abcNoneNonecde
I managed to get the desired output by adding ',':','
to the dictionary, like below. But wondering if there's another way of achieving the same?
d = {'1':'a', '2':'b', '3':'c', '4':'d', '5':'e'}
d[','] = ','
s = '123, 345'
m = [d.get(i) for i in s]
output = [str(i or ' ') for i in m]
print(''.join(map(str, output)))
# output -> abc, cde
Solution 1:[1]
Use i
as the default value for get
.
d = {'1':'a', '2':'b', '3':'c', '4':'d', '5':'e'}
s = '123, 345'
m = [d.get(i, i) for i in s]
print(''.join(map(str, m)))
Or all in one line.
print(''.join(d.get(i, i) for i in s))
We can drop the mapping to str
because all values are already a string.
Solution 2:[2]
Use the maketrans and translate functions
txt = "123, 345"
x = "12345"
y = "abcde"
mytable = txt.maketrans(x, y)
print(txt.translate(mytable))
This is the w3school link that explain the function: https://www.w3schools.com/python/ref_string_translate.asp
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | david medel |