2016-11-13 114 views
-2

我有一個電子表格,其文本值爲A067,A002,A104。什麼是最有效的方法來做到這一點?現在我做了以下內容:將字符串轉換爲Python中整數的最佳方法

str = 'A067' 
str = str.replace('A','') 
n = int(str) 
print n 
+0

這封信會永遠是A嗎?格式總是相同的,單個字母后跟3個數字? –

+0

什麼是模式?你什麼時候覺得可以提取一個有效的整數? 「Foo 42 Bar 81」是否包含一個或兩個或沒有整數? –

+0

我不能確定這封信是否總是'A'。以及我不能確定它總是3位數字,但我的猜測是它將基於我擁有的數據。 – MoreScratch

回答

0

如果輸入的唯一的非數字部分將是第一個字母,以最快的方式將可能是切片的字符串:

s = 'A067' 
n = int(s[1:]) 
print n 

如果你相信你會雖然每個字符串找到多個數字,但上面的正則表達式答案很可能更容易處理。

+0

謝謝。這完全符合我的情況。 – MoreScratch

1

根據數據,下面可能是合適的:

import string 

print int('A067'.strip(string.ascii_letters)) 

Python的strip()命令採用字符列表從開始和結束時取出一個字符串。通過傳遞string.ascii_letters,它將刪除字符串中的任何前後字母。

0

您可以使用正則表達式來查找數字。

import re 

s = 'A067' 
s = re.findall(r'\d+', s) # This will find all numbers in the string 
n = int(s[0]) # This will get the first number. Note: If no numbers will throw exception. A simple check can avoid this 
print n 

這裏的findall的一些輸出例如用不同的字符串

>>> a = re.findall(r'\d+', 'A067') 
>>> a 
['067'] 
>>> a = re.findall(r'\d+', 'A067 B67') 
>>> a 
['067', '67'] 
0

您可以使用正則表達式的替代方法,從重新模塊。

import re 
regex = re.compile("(?P<numbers>.*?\d+") 
matcher = regex.search(line) 
if matcher: 
    numbers = int(matcher.groupdict()["numbers"] #this will give you the numbers from the captured group 
0
import string 

str = 'A067' 
print (int(str.strip(string.ascii_letters))) 
相關問題