This question already has answers here:
How to implement conditional string formatting? [duplicate]
(3 answers)
Closed 1 year ago.
I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.
I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.
When I tried using round(3) it'll return 3.0.
Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?
Try choosing the format as a function of the values wholeness:
"{d}" if int(a) == a else "{:0:.2f}"
Can you finish from there?
You can use a conditional expression to choose the format based on the type of the variable:
for x in (33.3333333, 3):
print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
You could also implement it using a dictionary to map types to format strings:
formats = {int: "{:0}", float: "{:.2f}"}
for x in (33.3333333, 3):
print(formats.get(type(x)).format(x))
Related
This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 1 year ago.
I need to convert a string variable in the form of 'x / y', where x and y are arbitrary values in this string, into a numerical value. I'd assume that, using python, simply doing float('x/y') would allow for the interpretation of the division operation and thus yield a numerical value as the response, but instead, I am met with the following error:
ValueError: could not convert string to float: '7/100' (7 and 100 were the arbitrary values here)
Which suggests that this method is invalid. Is there any other way of doing this ? I thought of converting 'x' into an integer, then 'y' into an integer, and dividing the two integer values, but surely there's a better way of doing this.
>>> a = '4/10'
>>> float(eval(a))
0.4
But I would be careful with eval . It's not safe, you could probably use ast.literal_eval() instead
This question already has answers here:
Given n, take tsum of the digits of n. If that value has more than one digit, continue reducing a single-digit number is produced
(4 answers)
Closed 1 year ago.
I have problem and trying to get next:
new_string = "35" #and this result must be like new_int = 3+5.
How im available to do this? I know the type conversion, but not a clue how i should do this.
As you are new to the python, i suggest you doing it using
int(new_string[0]) # 3
int(new_string[1]) # 5
So now you have 2 integers, you can to whatever you want
This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 6 years ago.
i'd like to convert a decimal to a string, where zeros at the end are preserved.
Using str method erases the last zeros.
Example:
number=0.20
Goal: "0.20"
e.g. using: str(number)="0.2" doesn't seem to work.
If you want 2 decimal places use:
number = 0.20
str_number = '%.2f' % number
Number before f indicates the desired number of places.
This can be done using string formatting.
"{0:.2f}".format(number)
Will return 0.20.
Doing your chosen method won't work because upon declaring number = 0.20 it omits the last zero right away. If you put that into your idle:
number = 0.20
number
0.2
So declaring number as str(number) is doing str(0.2).
Use the % operator with an appropriate format string:
'%1.2f' % number
=> '0.20'
This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 3 years ago.
I'm trying to make length = 001 in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (length = 1). How would I stop this happening without having to cast length to a string before printing it out?
Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
It important to note that Python 2 is no longer supported.
Sample usage:
print(str(1).zfill(3))
# Expected output: 001
Description:
When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
Since python 3.6 you can use fstring :
>>> length = 1
>>> print(f'length = {length:03}')
length = 001
There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:
print(f"{1:03}")
Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.
To pad with zeros to a minimum of three characters, try:
length = 1
print(format(length, '03'))
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
This question already has answers here:
Most Pythonic way to print *at most* some number of decimal places [duplicate]
(3 answers)
Formatting floats without trailing zeros
(21 answers)
Closed 8 years ago.
I am using xlrd to read values from cells in an excel spreadsheet.
Whenever I detect a cell type = 2, then I know it is a number.
A number of 3 in cell will be returned as 3.0
And a number of 3.14 will be returned as 3.14
I will be converting numbers to text.
What function should I use to remove zeroes right of the decimal and the decimal?
The above 2 numbers should be 3 and 3.14
Use str.rstrip(), twice:
str_of_float.rstrip('0').rstrip('.')
This will remove trailing zeros, and if that leaves you with a trailing . it's removed as well.
Demo:
>>> '3.14'.rstrip('0').rstrip('.')
'3.14'
>>> '3.0'.rstrip('0').rstrip('.')
'3'
>>> '3000.0'.rstrip('0').rstrip('.')
'3000'
Don't be tempted to use .rstrip('.0'); it'll remove too many zeros:
>>> '3000.0'.rstrip('.0')
'3'
I always use format when printing values to strings. Using the format specs, it gives a good deal of control over what is printed.