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

后端 未结 6 2033
庸人自扰
庸人自扰 2020-11-28 06:42

I have several alphanumeric strings like these

listOfNum = [\'000231512-n\',\'1209123100000-n00000\',\'alphanumeric0000\', \'000alphanumeric\']
6条回答
  •  一个人的身影
    2020-11-28 07:22

    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]
    

提交回复
热议问题