比方说,我有一个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
你为什么不先试试自己,如果你确实向我们展示了你尝试过的代码? –