2017-02-26 176 views
-2

比方說,我有一個Python字符串是這樣的:Python將字符串轉換爲整數?

Some first text: 2342 
Another line here: 284 
Maybe third line: 458 
And forth line: 199 

,我想從這個字符串創建4個整數變量,使得VAR =(無論在線路1號)。和var2 =(第2行中的任何數字)..等等。

這怎麼可能?

+0

是的,有可能首先使用'split'和'int'來獲得你的號碼,然後使用'dictionary'來存儲它們。 – Arman

+0

@阿曼編輯:D – Madno

+0

你爲什麼不先試試自己,如果你確實向我們展示了你嘗試過的代碼? –

回答

2

您可以將所有編號的數組:

s = '''\ 
Some first text: 2342 
Another line here: 284 
Maybe third line: 458 
And forth line: 199''' 

print [int(l.split(':')[1]) for l in s.split('\n')] 

輸出:

[2342, 284, 458, 199] 

然後數組的第一個元素將對應於第一線等

0

試試這個:

words = somestring.split() 
    for i in range(len(words)): 
     try: 
      locals()['int_%s'%(i)] = int(words[i]) 
     exept: 
      pass 
0

您可以使用for循環和is_digit方法。

這樣的:

# let's guess input text is called TEXT. 
TEXT = '''\ 
Some first text: 2342 
Another line here: 284 
Maybe third line: 458 
And forth line: 199''' 

# we can make like this: 
splited_TEXT = TEXT.split('\n') 
# make new(wanted) dictionary 
new_dict = {} 

# then use for loop: 
for num, sentence in enumerate(splited_TEXT): 
    for word in sentence.split(' '): # split by space 
     if word.is_digit: # check if word is digit 
      new_dict[num] = word 
      continue 
print(new_dict) 

然後你就可以檢查{0:2342 1:284 ...}

0

我發現,這個簡單的線路工程:

[int(s) for s in TEXT.split() if s.isdigit()] 

爲如上所述的TEXT。

+0

沒錯,但是這並不回答第二部分,即創建變量。更普遍的解決方案會更好,因爲我不相信OP會知道數量(儘管也許它只是一個數字)。 :) – KeyWeeUsr

+0

對於4個數字,它將如下所示:var s1,var2,var3,var4 = [int(s)for s in TEXT.split()if s.isdigit()] – jnsod