[英]Append to a string with characters in a while loop python
我遇到了一個我無法在線解決的問題 - 我發現的所有答案只允許附加發生一次,因為它只是不斷重復相同的動作。
對於上下文:如果字符串不是 128 行長-我想將其填充到 128。所有填充應添加 00,然后移至下一行。 例如:
01
01
02
03
05
06
09
01
然后用 padding 應該變成
01
01
02
03
05
06
09
01
00
00
00
00 UP TO 128 lines
希望這能解釋我需要做什么。
我試過使用 .join 和 .ljust/.rjust。 在一個while循環內。 while循環是:
while count != 129:
padding.join("00\n")
count += 1
然而,它只打印出 00。任何建議表示贊賞。 謝謝!
your_string = "01\n01\n02\n03\n05\n06\n09\n01\n"
new_string = your_string + (128 - len(your_string.split())) * "01\n"
為了檢查行數,您需要計算“\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)
在您的示例中使用它:
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.