[英]Why does '' apparently evaluate as True in Python
I have: 我有:
raw_matrix.append([])
for as_string in ' '.split(line):
if as_string:
print('as_string: #' + as_string + '#')
raw_matrix[-1].append(int(as_string))
This produces the output: 产生输出:
as_string: # #
Traceback (most recent call last):
File "product_of_four", line 27, in <module>
raw_matrix[-1].append(int(as_string))
ValueError: invalid literal for int() with base 10: ''
raw_matrix is a 20x20 array of lines of two digit (decimal) numbers separated by spaces. raw_matrix是由空格分隔的两位数字(十进制)的行的20x20数组。
If I'm reading this correctly, as_string is evaluating to ' ' or '', and I'm getting an exception as a side effect of as_string not being parseable as the side effect of it not containing an int()-parseable digit string. 如果我正确地阅读了此内容,则as_string的计算结果为“”或“”,并且由于as_string的副作用无法解析而导致异常,因为它不包含int()可解析的数字字符串。
How can I change things so that Python 2.x (3.x) parses a string of two-digit integers, rather than trying to parse unparseable strings as integers? 如何更改内容,以便Python 2.x(3.x)解析一个两位整数的字符串,而不是尝试将不可解析的字符串解析为整数?
Thanks, 谢谢,
The line: 该行:
for as_string in ' '.split(line):
is pretty fishy here. 这里真是鱼腥 You're splitting the string
' '
on the delimiter line
, most likely returning the list [' ']
. 您正在分隔符
line
上分割字符串' '
,很可能返回列表[' ']
。 Remember that strings only evaluate to False-y values when they are empty (0 characters). 请记住,仅当字符串为空 (0个字符)时,它们的值才为False-y值。 The string
' '
is not empty (it has one character). 字符串
' '
不为空(它包含一个字符)。
You probably wanted to do something like: 您可能想要执行以下操作:
for as_string in line.split():
...
which will split line
on runs of consecutive whitespace. 它将在连续的空白
line
上分割line
。
You are using split the wrong way around; 您正在以错误的方式使用split; split the line, not the
' '
space: 分割线,而不是
' '
空格:
for as_string in line.split(' '):
By splitting the space character by line
delimiters, you invariably are going to end up with [' ']
, not an empty string: 通过用
line
定界符分隔空格字符,您将始终以[' ']
结尾,而不是空字符串:
>>> ' '.split('10 20 30')
[' ']
(the exceptions being an empty delimiter, not allowed, and splitting on ' '
, which gives you two empty strings instead). (例外情况是不允许使用空的定界符,并在
' '
上拆分,这会给您两个空字符串)。 And the one and only element in the result, ' '
, is a non-empty string, so True in a boolean context. 结果中的唯一元素
' '
是一个非空字符串,因此在布尔上下文中为True。
As for the error message, int()
ignores leading and trailing whitespace. 对于错误消息,
int()
忽略前导和尾随空格。 What is left is an empty string: 剩下的是一个空字符串:
>>> int(' ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
You probably want to even omit the ' '
argument wen splitting and just split on variable-width whitespace: 您甚至可能想省略
' '
参数wen split并只在可变宽度的空格上拆分:
for as_string in line.split():
leaving the first argument set to the default, None
. 将第一个参数设置为默认值
None
。 Using str.split()
also ignores any leading and trailing whitespace, always handy when reading lines from a file, those would include a newline: 使用
str.split()
也会忽略任何前导和尾随空格,从文件中读取行时总是很方便,这些行中应包含换行符:
>>> ' 10 20\t30\n'.split()
['10', '20', '30']
From the documentation: 从文档中:
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.如果未指定sep或为
None
,则将应用不同的拆分算法:连续的空白行将被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果在开头或结尾将不包含空字符串。 Consequently, splitting an empty string or a string consisting of just whitespace with aNone
separator returns[]
.因此,使用
None
分隔符拆分空字符串或仅包含空格的字符串将返回[]
。
Your split
statement is constructed incorrectly; 您的
split
语句构造不正确; it should be line.split(' ')
. 它应该是
line.split(' ')
。 The way it's written, you're trying to divide up a single space by whatever the contents of line
are, which is obviously just going to return the space. 它的编写方式是,您尝试根据
line
的内容划分单个空格,这显然只是要返回该空格。 That can't be evaluated as an integer. 不能将其评估为整数。
' '
evaluates to True because it is not an empty string (there is a space in there). ' '
计算结果为True,因为它不是一个空字符串(其中没有空格)。
The problem with your code is that for as_string in ' '.split(line)
should in fact be for as_string in ' '.split(line)
您的代码的问题是
for as_string in ' '.split(line)
中for as_string in ' '.split(line)
实际上应该for as_string in ' '.split(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.