[英]Append to a string with characters in a while loop python
I'm running into a problem which I cannot solve online- all answers I've found only allow the appending to happen once since it just keeps repeating the same action.我遇到了一个我无法在线解决的问题 - 我发现的所有答案只允许附加发生一次,因为它只是不断重复相同的动作。
For context: If a string isn't 128 lines long- I want to pad it out to reach 128. All padding should add 00 then move to the next line.对于上下文:如果字符串不是 128 行长-我想将其填充到 128。所有填充应添加 00,然后移至下一行。 For example:
例如:
01
01
02
03
05
06
09
01
Then with padding should become然后用 padding 应该变成
01
01
02
03
05
06
09
01
00
00
00
00 UP TO 128 lines
Hope that explains what I need to do.希望这能解释我需要做什么。
I've tried using .join and .ljust/.rjust.我试过使用 .join 和 .ljust/.rjust。 inside a while loop.
在一个while循环内。 The while loop is:
while循环是:
while count != 129:
padding.join("00\n")
count += 1
However it only ever prints out 00. Any advice is appreciated.然而,它只打印出 00。任何建议表示赞赏。 Thank you!
谢谢!
your_string = "01\n01\n02\n03\n05\n06\n09\n01\n"
new_string = your_string + (128 - len(your_string.split())) * "01\n"
In order to check the number of lines you need to count the number of "\n" occurrences.为了检查行数,您需要计算“\n”出现的次数。 Since the string seems to be a variable amount you need to be able to do this dynamically.
由于字符串似乎是可变数量,因此您需要能够动态地执行此操作。 You would have to write a function to check this.
您必须编写一个函数来检查这一点。
something like this should work像这样的东西应该工作
def pad_string(unpadded_string, string_length =128, pad_string ='00\n'):
"""Function to ensure that a string is ``string_length`` lines.
Do this by counting the number of new lines and appending deliminator where neccesary"""
num_lines = unpadded_string.count('\n')
if not num_lines < string_length:
return unpadded_string
return unpadded_string + pad_string*(string_length-num_lines)
Using this in your example:在您的示例中使用它:
your_string = "01\n01\n02\n03\n05\n06\n09\n01\n"
def pad_string(unpadded_string, string_length =128, pad_string ='00\n'):
"""Function to ensure that a string is ``string_length`` lines.
Do this by counting the number of new lines and appending deliminator where neccesary"""
num_lines = unpadded_string.count('\n')
if not num_lines < string_length:
return unpadded_string
return unpadded_string + pad_string*(string_length-num_lines)
print(pad_string(your_string).count('\n'))
>>> 128
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.