简体   繁体   English

Python 字符串从第一个非零字符拆分

[英]Python string split from first non-zero character

I have a string in Python such as;我在 Python 中有一个string ,例如;

'00000001890573'

I want to extract the 1890573 (from first non-zero character to the last character in the string).我想提取1890573 (从第一个非零字符到字符串中的最后一个字符)。

I tried to split like this;我试着这样分裂; '00000001890573'.split('0') .. It gives me ['', '', '', '', '', '', '', '189', '573'] '00000001890573'.split('0') .. 它给了我['', '', '', '', '', '', '', '189', '573']

But this is not what I want!!但这不是我想要的!! Because if I combine the last two string I will not get 1890573 .因为如果我结合最后两个字符串,我将不会得到1890573

You can use the strip() built-in method.您可以使用strip()内置方法。

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

I think I got it!!我想我明白了!!

int('00000001890573')

Another way is to use the Python re module:另一种方法是使用 Python re模块:

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.这会找到从 1 到 9 的第一个数字,然后包括字符串的 rest 直到行尾。

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:完成此操作的最简单方法是将字符串转换为 integer,对其进行四舍五入,然后将其转换回字符串,如下所示:

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.但是,这仅在它是 integer 时才有效,就好像它不是小数位将被截断,并且数字将四舍五入到最接近的 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:如果您还需要它来处理小数,一个可能的答案是使用 for 循环,尽管如果您执行很多循环,这可能会变得低效:

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.我在 3.7 中测试了这两种解决方案,据我所知,它应该适用于 Python 的所有版本。

Hope this helped!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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