简体   繁体   English

如何从字母数字字符串中提取有效数字?

[英]How to extract significant numeric digits from an alphanumeric string?

I have an ID DIS002789.I want to extract 2789 from the given ID.I have to use the extracted number in a for loop using a variable. 我有一个ID DIS002789。我想从给定的ID中提取2789.我必须在for循环中使用变量使用提取的数字。

I tried using re.findall. 我尝试使用re.findall。

inputk='DIS0002789'
non_decimal = re.findall(r'[\d.]+', inputk)
for n in range(non_decimal, non_decimal + 1000):

Im getting 002789. But I want my output to be 2789.And also i cant use the for loop because of this.It shows an error saying 002789 is an invalid syntax. 我收到002789。但是我希望我的输出是2789。而且由于这个原因,我也不能使用for循环。它显示了一个错误,指出002789是无效的语法。 I tried converting it to int. 我尝试将其转换为int。 but its shows the following error, TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' 但它显示以下错误TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“列表”

you can pass the result of re.findall(r'[\\d.]+', inputk) to int in order to make it an integer. 您可以将re.findall(r'[\\d.]+', inputk)传递给int以使其为整数。 int('0123') will ignore leading zeroes. int('0123')将忽略前导零。

Example: 例:

inputk='DIS0002789'
non_decimal = int(re.findall(r'[\d.]+', inputk))

if you want it to be a string you can pass it to str again: str(int('0123')) == '123' 如果您希望它是字符串,则可以再次将其传递给strstr(int('0123')) == '123'

If you want the int value, you should convert it to integer as other answers show. 如果需要int值,则应将其转换为整数,如其他答案所示。 If you only want the string, you can try adding the optional leading zeros: 如果只需要字符串,则可以尝试添加可选的前导零:

inputk='DIS0002789'
non_decimal = re.findall(r':?[0]*(\d+)', inputk)
non_decimal

output: 输出:

['2789']

you can ignore leading zeros and convert it to an integer to use in a loop 您可以忽略前导零并将其转换为整数以在循环中使用

inputk='DIS0002789'
non_decimal = int(re.findall(r':?[0]*(\d+)', inputk)[0])

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

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