简体   繁体   English

将不同数量的字符附加到字符串列表中的字符串

[英]Append differing number of characters to strings in list of strings

Let's say I have a list of strings: 假设我有一个字符串列表:

strs = ["aa", "bbb", "c", "dddd"]

I want to append spaces to the end of each string so that each string is 4 characters long. 我想在每个字符串的末尾添加空格,以便每个字符串长度为4个字符。 That is, I want the end product to look like this: 也就是说,我希望最终产品看起来像这样:

strs_final = ["aa  ", "bbb ", "c   ", "dddd"]

I think list comprehension is the way to go, but I'm not sure exactly how to go about doing this. 我认为列表理解是要走的路,但我不确定如何去做这件事。 I know how to, for instance, pick out the strings that are of length 3 and add one space to them: 我知道如何挑选长度为3的字符串并为它们添加一个空格:

[i+" " for i in strs if len(i) == 3]

But I don't know how to add varying numbers of spaces for varying lengths of strings 但我不知道如何为不同长度的字符串添加不同数量的空格

另一种解决方案是使用str.ljust

[i.ljust(4) for i in strs]

You can use python's format . 你可以使用python的format The general form for format specifier is: 格式说明符的一般形式是:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

so, if you provide the width it will be padded with space: 所以,如果你提供width ,它将填充空格:

>>> list(map('{:4}'.format, strs))
['aa  ', 'bbb ', 'c   ', 'dddd']
>>> [i+" "*(4-len(i)) for i in strs]
['aa  ', 'bbb ', 'c   ', 'dddd']

The key point being "x"*4 gives you "xxxx" 关键点是"x"*4给你"xxxx"

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

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