[英]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?
I'm very new to coding and im learning python and I have a certain problem.我对编码和学习 python 很陌生,我有一个问题。 I'm writing a program which requires the user to input an amount and I want the program to always print out 15 zeros but I want the amount the user inputs to replace the zeros starting from the end.
我正在编写一个程序,它要求用户输入一个数量,并且我希望程序始终打印出 15 个零,但我希望用户输入的数量从末尾开始替换零。 For example, if the user enters
43525
.例如,如果用户输入
43525
。 The program would print 000000000043525
该程序将打印
000000000043525
Also for example if the user inputs 2570.20
The program would print 000000000257020
(removes dot automatically)例如,如果用户输入
2570.20
程序将打印000000000257020
(自动删除点)
can anyone help me with how I should go about doing this?任何人都可以帮助我如何 go 这样做?
you can use .replace()
to remove any decimal point and .rjust()
to add the right number of zeros您可以使用
.replace()
删除任何小数点, .rjust()
添加正确数量的零
print(input('number: ').replace('.', '').rjust(15, '0'))
You can just use simple string manipulations to do this.您可以使用简单的字符串操作来执行此操作。 For example:
例如:
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))
Using list slicing使用列表切片
added_string = added_string.replace(".", "") new_str = start_string[:len(start_string) - len(added_str)] + added_string added_string = added_string.replace(".", "") new_str = start_string[:len(start_string) - len(added_str)] + added_string
You can use zfill
for this:您可以为此使用
zfill
:
print(''.join(input('Enter number: ').split('.')).zfill(15))
You can add leading 0s by using this string formatting while printing:您可以在打印时使用此字符串格式添加前导 0:
print("%015d" % (int(number),))
This means 0s will be added until 15 characters are printed.这意味着将添加 0 直到打印 15 个字符。 For the removal of decimal dot you can use string replace method:
对于删除小数点,您可以使用字符串替换方法:
number = str(number).replace('.', '')
This should get you started.这应该让你开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.