【问题标题】:Unable to get fractional portion of some tuples无法获取某些元组的小数部分
【发布时间】:2020-07-21 09:23:09
【问题描述】:

我有一个文本文件,它在元组的不同行中包含不同的信息。我希望得到每个元组的' ' 内的小数部分。

文本文件中的数据如下:

('Corredor Sanchez', 'Clara', '663354212','email@something.com')
('Berea Castejon', 'Jorge', '934518811',''email@something.com'')
('Juarez Cruz', 'Veronica', '',''email@something.com'')

我希望得到的预期输出:

Corredor Sanchez, Clara, 663354212, email@something.com
and so on -----

我试过了:

with open("data.txt","r") as f:
    for item in f.readlines():
        container = item.strip()
        last_name = container[0]
        print(last_name)
        break

当我运行上面的脚本时,我得到了(

如何修改脚本以获得上面显示的输出?

【问题讨论】:

  • 您的文本文件包含 text

标签: python python-3.x indexing tuples


【解决方案1】:

您可以使用 ast.literal_eval 以字符串形式解析(有效的 Python)文字:

import ast

with open("data.txt","r") as f:
    for item in f.readlines():
        container = ast.literal_eval(item.strip())
        last_name = container[0]
        print(last_name)
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多