簡體   English   中英

如何從字母數字字符串中提取有效數字?

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

我有一個ID DIS002789。我想從給定的ID中提取2789.我必須在for循環中使用變量使用提取的數字。

我嘗試使用re.findall。

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

我收到002789。但是我希望我的輸出是2789。而且由於這個原因,我也不能使用for循環。它顯示了一個錯誤,指出002789是無效的語法。 我嘗試將其轉換為int。 但它顯示以下錯誤TypeError:int()參數必須是字符串,類似字節的對象或數字,而不是“列表”

您可以將re.findall(r'[\\d.]+', inputk)傳遞給int以使其為整數。 int('0123')將忽略前導零。

例:

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

如果您希望它是字符串,則可以再次將其傳遞給strstr(int('0123')) == '123'

如果需要int值,則應將其轉換為整數,如其他答案所示。 如果只需要字符串,則可以嘗試添加可選的前導零:

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

輸出:

['2789']

您可以忽略前導零並將其轉換為整數以在循環中使用

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