Hello everyone,
I am still new to python and learning.
So I practiced some exercises and made an app that calculates the percentage from the number the user enters.
My question use, how can I terminate the .0 part if the user enters an Int and keep the decimal part if they enter a float?
so for example, 5% of 100 is 5 ( Int)
and 5.1% of 100 is 5.1 (float)
What about a basic
your_string.strip("0")
to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).
More info in the doc.
You could use some list comprehension to get the sequences you want like so:
trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]
Remove leading + trailing '0':
list = [i.strip('0') for i in list_of_num]
Remove leading '0':
list = [i.lstrip('0') for i in list_of_num]
Remove trailing '0':
list = [i.rstrip('0') for i in list_of_num]
How to remove the .0 in a integter in python - Stack Overflow
Remove the leading zero before a number in python - Stack Overflow
How to terminate or remove the .0 point from an int.
pandas question: how can I preserve leading zeros after saving to a CSV?
Videos
Use int function to cast your float number to int:
int(794.0) # 794
and in your program try this program_widths = int(program_widths) if you want your variable become int if you want just print it as int just cast to int for print -> print int(program_widths)
It's because it is a float. If you want an integer, you need to convert it:
int(variable)
I'm not sure what you're trying to do here though.
Use lstrip:
>>> '00000010'.lstrip('0')
'10'
(strip removes both leading and trailing zeros.)
This messes up '0' (turning it into an empty string). There are several ways to fix this:
#1:
>>> re.sub(r'0+(.+)', r'\1', '000010')
'10'
>>> re.sub(r'0+(.+)', r'\1', '0')
'0'
#2:
>>> str(int('0000010'))
'10'
#3:
>>> s = '000010'
>>> s[:-1].lstrip('0') + s[-1]
just use the int() function, it will change the string into an integer and remove the zeros
my_str = '00000010'
my_int = int(my_str)
print(my_int)
output:
10