奇怪的Delimi

2024-04-26 01:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我试图解析一个文件和单独的值,但是,我使用了一个奇怪的分隔符。有人能帮忙吗?谢谢!你知道吗

我正在分析的文件中的行类似于:

john-burk AL
john-smith    CA
john-joe    FL
john-john  TX

当前代码:

with open('info.txt', 'r') as f:
    for line in f:
        try:
            name, state = line.split(<do not know what to use>)
        except Exception as e:
            print "[-] Error parsing data " + str(e)

预期产量:

name = "john-burk"
state = "AL"

Tags: 文件代码nameaslinejohncastate
1条回答
网友
1楼 · 发布于 2024-04-26 01:04:57

引用^{}文档

str.split([sep[, maxsplit]])If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

所以,你可以简单地

name, state = line.split()
print name, state

由于我们没有指定分隔符,Python将根据任意数量的连续空格字符作为分隔符进行拆分。因此,您的数据可以分为namestate

注意:如果name有任何空格字符,这将不起作用。你知道吗

相关问题 更多 >