从没有空格的文件分割字符串

时间:2022-07-03 21:37:59

I am trying to split the first line of the file into 3 separate values but it gives me an error

我试图将文件的第一行分割成3个单独的值,但它给了我一个错误

ValueError: not enough values to unpack (expected 3, got 1)

ValueError:没有足够的值解包(预期是3,得到1)

#open files
infile = open("milkin.txt","r").readlines()
outfile = open("milkout.txt","w")


#instantiate variables
a,b,c = infile[0].split()

milkin.txt

milkin.txt

abc
def
ghi

1 个解决方案

#1


2  

First, split() uses whitespace by default if no argument is specified.

首先,如果没有指定参数,split()默认使用空格。

>>> 'abc'.split()
['abc']

Fortunately, to unpack a string into multiple values you do not need to split() the string. Since a string is itself iterable, you can unpack multiple values so long as you can ensure the length of the string matches the number of declaring variables.

幸运的是,要将字符串解压缩为多个值,不需要拆分()字符串。由于字符串本身是可迭代的,所以只要您能够确保字符串的长度与声明变量的数量相匹配,就可以解压多个值。

>>> a, b, c = 'abc'
>>> a
'a'
>>> b
'b'
>>> c
'c'

Also, the readlines() method of a file object returns a list of strings that contain a trailing newline character, so what you might think is just the string 'abc' at infile[0] is really 'abc\n'.

此外,文件对象的readlines()方法返回一个字符串列表,其中包含一个尾换行字符,因此您可能认为infile[0]上的字符串“abc”实际上是“abc\n”。

This should work:

这应该工作:

a, b, c = infile[0].strip()

#1


2  

First, split() uses whitespace by default if no argument is specified.

首先,如果没有指定参数,split()默认使用空格。

>>> 'abc'.split()
['abc']

Fortunately, to unpack a string into multiple values you do not need to split() the string. Since a string is itself iterable, you can unpack multiple values so long as you can ensure the length of the string matches the number of declaring variables.

幸运的是,要将字符串解压缩为多个值,不需要拆分()字符串。由于字符串本身是可迭代的,所以只要您能够确保字符串的长度与声明变量的数量相匹配,就可以解压多个值。

>>> a, b, c = 'abc'
>>> a
'a'
>>> b
'b'
>>> c
'c'

Also, the readlines() method of a file object returns a list of strings that contain a trailing newline character, so what you might think is just the string 'abc' at infile[0] is really 'abc\n'.

此外,文件对象的readlines()方法返回一个字符串列表,其中包含一个尾换行字符,因此您可能认为infile[0]上的字符串“abc”实际上是“abc\n”。

This should work:

这应该工作:

a, b, c = infile[0].strip()