gpt4 book ai didi

python - 奇怪的分隔符

转载 作者:行者123 更新时间:2023-12-01 04:43:08 24 4
gpt4 key购买 nike

在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"

最佳答案

引用str.split文档,

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

注意:如果名称包含任何空白字符,则此操作将不起作用。

关于python - 奇怪的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com