簡體   English   中英

如何將字符串中的一定數量的零替換為要求用戶輸入的數量,從字符串的末尾開始?

[英]How do I replace a certain amount of zeros in a string with an amount that the user is asked to input, starting from the end of the string?

我對編碼和學習 python 很陌生,我有一個問題。 我正在編寫一個程序,它要求用戶輸入一個數量,並且我希望程序始終打印出 15 個零,但我希望用戶輸入的數量從末尾開始替換零。 例如,如果用戶輸入43525 該程序將打印000000000043525

例如,如果用戶輸入2570.20程序將打印000000000257020 (自動刪除點)

任何人都可以幫助我如何 go 這樣做?

您可以使用.replace()刪除任何小數點, .rjust()添加正確數量的零

print(input('number: ').replace('.', '').rjust(15, '0'))

您可以使用簡單的字符串操作來執行此操作。 例如:

k = 212.12

if '.' in str(k):
    string = str(k).replace('.','')
    print('0'*(15-len(string))+string)

else:
    print('0'*(15-len(str(k)))+str(k))

使用列表切片

added_string = added_string.replace(".", "") new_str = start_string[:len(start_string) - len(added_str)] + added_string

您可以為此使用zfill

print(''.join(input('Enter number: ').split('.')).zfill(15))

您可以在打印時使用此字符串格式添加前導 0:

print("%015d" % (int(number),))

這意味着將添加 0 直到打印 15 個字符。 對於刪除小數點,您可以使用字符串替換方法:

number = str(number).replace('.', '')

這應該讓你開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM