简体   繁体   English

如何从输出中删除空格,但保留python中的字典值?

[英]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 : 除了建议使用join而不是使用循环的其他答案外,您还可以使用str.translate获得所需的输出:

>>> 'abcd'.translate(str.maketrans({'a': '1', 'b': '2', 'c': '3', 'd': ' '}))
'123 '

And if you are in python 2 you can do the following : 如果您使用的是python 2,则可以执行以下操作:

>>> 'abcd'.translate(string.maketrans('abcd','123 '))
'123 '

or you can extract the input and out put for create your table, from dict : 或者您可以从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 : 只需将dict.get与带有str.join的空字符串的默认值一起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: 如果您使用repr,则可以看到以下空格:

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. 另外,请避免将dict作为变量名使用,否则像dict(foo="bar")将无法达到您的预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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