简体   繁体   中英

How do I convert a number to a string in the same format as the input in python?

Consider the following lines:

a = 5e7
print(str(a))

I get 50000000.0 instead of 5e7 itself, can I do this using str command itself ?

You are able to write in another way too. I prefer using this method because it is clearer.

a = 5e7
print(f"{a:0.0e}")

However if you have more than one int or float to be used in a sentence, you can write it something like this.

print("{a:0.0e} ... {a:0.0e}".format(a = 5e7))

The code above will give u 2 var "a"

For more codes please check

https://www.w3schools.com/python/ref_string_format.asp

Hopefully this will help u.

There is no way of knowing the format of the original input, since only the type and value are remembered during parsing.

However, if you are looking for how to display a number in exponential form, use the e format specifier, like this:

a = 5e7
print("{:0.0e}".format(a))

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