Python从文件中读取字符串并将其拆分为值 [英] Python read in string from file and split it into values
本文介绍了Python从文件中读取字符串并将其拆分为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式如下的文件:
I have a file in the format below:
995957,16833579
995959,16777241
995960,16829368
995961,50431654
我想读每一行,但将这些值分成适当的值.例如,第一行将被拆分为:
I want to read in each line but split the values into the appropriate values. For example the first line would be split into:
x = 995957
y = 16833579
由于当您读入它时它是一个字符串,并且我想将它们转换为一个int并将它们拆分,所以我该怎么做呢?任何帮助将不胜感激.
Since its a string when you read it in and I want to convert them to an int and split them, how exactly would I go about doing this? Any help would be appreciated.
谢谢!
推荐答案
类似的事情-对于读入字符串变量a
的每一行:
Something like this - for each line read into string variable a
:
>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456
现在,您可以对分配的x
和y
(它们是整数)进行必要的操作.
Now you can do what is necessary with x
and y
as assigned, which are integers.
这篇关于Python从文件中读取字符串并将其拆分为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文