简体   繁体   中英

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. 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. For example, if the user enters 43525 . The program would print 000000000043525

Also for example if the user inputs 2570.20 The program would print 000000000257020 (removes dot automatically)

can anyone help me with how I should go about doing this?

you can use .replace() to remove any decimal point and .rjust() to add the right number of zeros

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

You can use zfill for this:

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

You can add leading 0s by using this string formatting while printing:

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

This means 0s will be added until 15 characters are printed. For the removal of decimal dot you can use string replace method:

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

This should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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