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]
Answer from Pierre GM on Stack OverflowWhat 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 can I get the "format" function to leave my leading ZEROs in place?
Remove the leading zero before a number in python - Stack Overflow
How do I write a Regex in Python to remove leading zeros for a number in the middle of a string - Stack Overflow
python 3.x - How can I format a string to remove leading zeros? - Stack Overflow
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
You can use
re.sub(r'^\D*0*', '', text)
See the regex demo. Details
^- start of string\D*- any zero or more non-digit chars0*- zero or more zeros.
See Python demo:
import re
text = "U012034"
print( re.sub(r'^\D*0*', '', text) )
# => 12034
If there is more text after the first number, use
print( re.sub(r'^\D*0*(\d+).*', r'\1', text) )
See this regex demo. Details:
^- start of string\D*- zero or more non-digits0*- zero or more zeros(\d+)- Group 1: one or more digits (use(\d+(?:\.\d+)?)to match float or int values)- `.* - the rest of the string.
The replacement is the Group 1 value.
You may use this re.sub in Python:
string = re.sub(r'^[a-zA-Z]*0*|[a-zA-Z]+', '', string)
RegEx Demo
Explanation:
^: Start[a-zA-Z]*: Match 0 or more letters0*L: Match 0 or more zeroes|: OR[a-zA-Z]+: Match 1+ of letters
My motivation here is to parse a string and do some calculations with the time of day...for instance 6:05 . I could just use split() and have hour="6" and minute ="05"but if I understand correctly, leading zeros won't work for calculations. I could use a method to convert to an integer to do it but saw that some people just loop through like this:
txt = "6:05"
x, y= (int(i) for i in txt.split(":"))
print(x)
print(y)
#answer:
#6
#5So what is happening here exactly? I'm guessing the int(i) converts the string "05" into the integer 5 somehow but can't find the syntax for that when i've been searching for python loops and splits. If someone could explain this, I would appreciate it.
*edit*, thanks for the help guys!
from datetime import datetime
print(f'{datetime.now():%A, %B %d, %Y %I:%M %p}')This will give me something like.
Wednesday, November 09, 2022 06:17 PM
Is there a simple way to suppress the leading zeroes from day of month and hour in the above?
Here is another way:
>>> ("%.4f" % k).lstrip('0')
'.1337'
It is slightly more general than [1:] in that it also works with numbers >=1.
Neither method correctly handles negative numbers, however. The following is better in this respect:
>>> re.sub('0(?=[.])', '', ("%0.4f" % -k))
'-.1337'
Not particularly elegant, but right now I can't think of a better method.
As much as I like cute regex tricks, I think a straightforward function is the best way to do this:
def formatFloat(fmt, val):
ret = fmt % val
if ret.startswith("0."):
return ret[1:]
if ret.startswith("-0."):
return "-" + ret[2:]
return ret
>>> formatFloat("%.4f", .2)
'.2000'
>>> formatFloat("%.4f", -.2)
'-.2000'
>>> formatFloat("%.4f", -100.2)
'-100.2000'
>>> formatFloat("%.4f", 100.2)
'100.2000'
This has the benefit of being easy to understand, partially because startswith is a simple string match rather than a regex.
You could use %g to achieve this:
'%g'%(3.140)
or, with Python ≥ 2.6:
'{0:g}'.format(3.140)
or, with Python ≥ 3.6:
f'{3.140:g}'
From the docs for format: g causes (among other things)
insignificant trailing zeros [to be] removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
Me, I'd do ('%f' % x).rstrip('0').rstrip('.') -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g, but, it works (and I don't know how to force %g to never use scientific notation;-).