为什么以下命令会使用breakline生成输入。看起来隔行线出现在{}
之后。我之前使用了format
函数,它工作正常。现在发生什么事?使用str.format打印时出现不规则的换行符
print('true: {}, estimated: {}'.format(number_a, number_b))
true: 3
, estimated: 3
为什么以下命令会使用breakline生成输入。看起来隔行线出现在{}
之后。我之前使用了format
函数,它工作正常。现在发生什么事?使用str.format打印时出现不规则的换行符
print('true: {}, estimated: {}'.format(number_a, number_b))
true: 3
, estimated: 3
我的猜测是你从文件中读取这些数字,这意味着你的字符串'3\n'
而不是数量3
中读出。
尝试用str.strip
删除尾部换行符:
print('true: {}, estimated: {}'.format(number_a.rstrip(), number_b))
一个更好的办法是,当你读它在消毒你的数据,所以你不必担心这样的事情。
numbers = []
with open(...) as f:
for line in f:
numbers.append(line.strip())
a, b = numbers[:2] # first two elements
print('true: {}, estimated: {}'.format(a, b))
显然,你的数据可能不遵循此示例中的格式,但外卖是从源头来处理这些事情。
我无法重现此问题。你的变量number_a
和number_b
字符串有没有机会?如果是,它可能包含一个新行。 试试这个:
print('true: {}, estimated: {}'.format(int(number_a), int(number_b)))
例子:
number_a = '4\n'
number_b = '5'
print('true: {}, estimated: {}'.format(int(number_a), int(number_b)))
输出:
true: 4, estimated: 5
'型(NUMBER_A)' – nu11p01n73R
能否打印'它自己请number_a'。它实际上是一个整数,还是它是一个尾随换行符的字符串? –