简体   繁体   中英

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 .

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

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

I think I got it!!

int('00000001890573')

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM