Reputation: 891
I have to remove the spaces and newlines in the output, but need the spaces that are values in the dictionary.
code:
dict = {'a': '1', 'b': '2', 'c': '3', 'd': ' '}
strg = 'abcd'
for i in strg:
if i in dict:
print (dict.get(i,)),
I get the following output:
1 2 3 space
what I want is:
123space
Upvotes: 1
Views: 61
Reputation: 107297
Along side the other answers that suggests join
instead of using loops you can use str.translate
for get the desire output :
>>> 'abcd'.translate(str.maketrans({'a': '1', 'b': '2', 'c': '3', 'd': ' '}))
'123 '
And if you are in python 2 you can do the following :
>>> 'abcd'.translate(string.maketrans('abcd','123 '))
'123 '
or you can extract the input and out put for create your table, from dict :
>>> d={'a': '1', 'b': '2', 'c': '3', 'd': ' '}
>>> inp=''.join(d.keys())
>>> out=''.join(d.values())
>>> 'abcd'.translate(string.maketrans(inp,out))
'123 '
Upvotes: 4
Reputation: 180441
Just use dict.get
with a default value of an empty string with str.join
:
d = {'a': '1', 'b': '2', 'c': '3', 'd': ' '}
strg = 'abcd'
print("".join(d.get(i,"") for i in strg))
If you use repr you can see the space:
print(repr("".join(d.get(i,"") for i in strg)))
'123 '
Also avoid using dict as a variable name or something likedict(foo="bar")
will not do what you think it will.
Upvotes: 3