简体   繁体   中英

How to remove spaces from output but retain those that are dictionary values in python?

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

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 '

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 like dict(foo="bar") will not do what you think it will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM