Mass17
Mass17

Reputation: 1605

Python string split from first non-zero character

I have a string in Python such as;

'00000001890573'

I want to extract the 1890573 (from first non-zero character to the last character in the string).

I tried to split like this; '00000001890573'.split('0').. It gives me ['', '', '', '', '', '', '', '189', '573']

But this is not what I want!! Because if I combine the last two string I will not get 1890573.

Upvotes: 1

Views: 874

Answers (4)

Nether Man
Nether Man

Reputation: 80

The simplest method to accomplish this would be by turning the string into an integer, rounding it, and then converting it back to a string, like so:

string = "00000001890573"
answer = round(int(string))
answer = str(answer)

However, this would only work if it is an integer, as if it is not the decimal places would be cut off and the number would be rounded to the nearest integer.

If you need it to work for decimals as well, a possible answer is to use a for loop, although this could potentially become inefficient if you do a lot of them:

string = "00000001890573"
for i in range(len(string)):
     if(string[i] != "0"):
          string = string[i:len(string)]
          break

I tested both of these solutions in 3.7, and it should work in all versions of Python as far as I'm aware.

Hope this helped!

Upvotes: 1

Lyndon Gingerich
Lyndon Gingerich

Reputation: 655

Another way is to use the Python re module:

re.search('[1-9].*$', '00000001890573')

This finds the first digit from 1 to 9, then includes the rest of the string until the end of the line.

Upvotes: 1

Mass17
Mass17

Reputation: 1605

I think I got it!!

int('00000001890573')

Upvotes: 1

MzdR
MzdR

Reputation: 188

You can use the strip() built-in method.

st = '00000001890573'
st.lstrip('0')

Upvotes: 5

Related Questions