比方說,我有一個Python字符串是這樣的:Python將字符串轉換爲整數?
Some first text: 2342
Another line here: 284
Maybe third line: 458
And forth line: 199
,我想從這個字符串創建4個整數變量,使得VAR =(無論在線路1號)。和var2 =(第2行中的任何數字)..等等。
這怎麼可能?
比方說,我有一個Python字符串是這樣的:Python將字符串轉換爲整數?
Some first text: 2342
Another line here: 284
Maybe third line: 458
And forth line: 199
,我想從這個字符串創建4個整數變量,使得VAR =(無論在線路1號)。和var2 =(第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]
然後數組的第一個元素將對應於第一線等
試試這個:
words = somestring.split()
for i in range(len(words)):
try:
locals()['int_%s'%(i)] = int(words[i])
exept:
pass
您可以使用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 ...}
是的,有可能首先使用'split'和'int'來獲得你的號碼,然後使用'dictionary'來存儲它們。 – Arman
@阿曼編輯:D – Madno
你爲什麼不先試試自己,如果你確實向我們展示了你嘗試過的代碼? –