1

I am currently getting a list of random numbers that end with a random len of 0’s in Python 3.x. So for example, I get the following set of random string of numbers:

String 1 = 203502000000
String 2 = 302933000
String 3 = 000023123389270

Is there a way to remove the series of 0’s found at the end of each string without deleting any other series of 0’s such as those found in the beginning of String 3? Thank you.

user3483203
  • 50,081
  • 9
  • 65
  • 94
Nick Oh
  • 25
  • 4

2 Answers2

2

Assuming that your variables are strings like you claim, and not integers like they are in the question, you are looking for rstrip:

>>> s1 = '203502000000'
>>> s1.rstrip('0')
'203502'

This will remove all trailing zeros from the string, but none anywhere else.

To apply this to your entire list, you may use a list comprehension:

[s.rstrip('0') for s in my_list]
user3483203
  • 50,081
  • 9
  • 65
  • 94
0

String manipulation method

You could use the fact that leading zeros are ignored when casting to an integer. As such, you would reverse your string, make an integer cast, then cast back to a string, and reverse it again. Here's an example:

In [20]: s
Out[20]: '125647124004170000'

In [21]: s[::-1]
Out[21]: '000071400421746521'

In [22]: int(_)
Out[22]: 71400421746521

In [23]: str(_)
Out[23]: '71400421746521'

In [24]: _[::-1]
Out[24]: '12564712400417'

In lines 21 and 24, we use a complete slice with a step of -1, which reverses the string.

As a one-liner list comprehension, you could do the following with your string s:

[str(int(s[::-1]))[::-1] for s in strings_list]

Numerical method

A simple way to do that would be to divide the integer cast of your strings by 10 using integer division until the time integer division produces a different result from floating point division. After we're done, we convert it back to a string, if your use case so requires it. The time it takes is linear in terms of the number of zeros at the end. Worst, case, O(n), where n is the length of your string.

In [7]: s = '125647124004170000'

In [8]: b = int(s)
Out[8]: 125647124004170000

(modified after @AChampion's comment)

In [9]: while b % 10 == 0:
   ...:     b //= 10

In [10]: b
Out[10]: 12564712400417

In [11]: str(b)
Out[11]: '12564712400417'
axolotl
  • 1,042
  • 1
  • 12
  • 23
  • A better numerical approach would be `while b % 10 == 0: b //= 10`, this keeps everything in the integer space. – AChampion Jul 15 '18 at 00:54
  • It is mathematically the same, but true, cleaner code. Let me incorporate that into the answer. – axolotl Jul 15 '18 at 00:55
  • This is not mathematically the same, you are assuming that you don't introduce comparison challenges due to float arithmetic, try `0.1 + 0.2 == 0.3` - see: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – AChampion Jul 15 '18 at 00:57