[python] How to remove leading and trailing zeros in a string? Python

I have several alphanumeric strings like these

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']

The desired output for removing trailing zeros would be:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

The desired output for leading trailing zeros would be:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']

The desire output for removing both leading and trailing zeros would be:

listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', 'alphanumeric']

For now i've been doing it the following way, please suggest a better way if there is:

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []

# Remove trailing
for i in listOfNum:
  while i[-1] == "0":
    i = i[:-1]
  trailingremoved.append(i)

# Remove leading
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  leadingremoved.append(i)

# Remove both
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  while i[-1] == "0":
    i = i[:-1]
  bothremoved.append(i)

This question is related to python string trailing chomp leading-zero

The answer is


You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

str.strip is the best approach for this situation, but more_itertools.strip is also a general solution that strips both leading and trailing elements from an iterable:

Code

import more_itertools as mit


iterables = ["231512-n\n","  12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']

Details

Notice, here we strip both leading and trailing "0"s among other elements that satisfy a predicate. This tool is not limited to strings.

See also docs for more examples of

more_itertools is a third-party library installable via > pip install more_itertools.


Remove leading + trailing '0':

list = [i.strip('0') for i in listOfNum ]

Remove leading '0':

list = [ i.lstrip('0') for i in listOfNum ]

Remove trailing '0':

list = [ i.rstrip('0') for i in listOfNum ]

Did you try with strip() :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'

e.g

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to trailing

Remove Trailing Spaces and Update in Columns in SQL Server JAVA How to remove trailing zeros from a double How to remove leading and trailing zeros in a string? Python How do I remove trailing whitespace using a regular expression? How can I remove a trailing newline?

Examples related to chomp

How to remove leading and trailing zeros in a string? Python

Examples related to leading-zero

How to remove leading and trailing zeros in a string? Python How to concatenate strings with padding in sqlite Javascript add leading zeroes to date