在python中将len()组合为字符串时,结果中出现意外的空格



新来的编程学生!我不明白为什么这个代码返回"troy aikman赢了"。特洛伊·艾克曼不是"赢了"而是"赢了"。&quot后没有空格。won"我假设它与" len()"部分。我把逗号换成了"+"这给了我一个错误(正如我所想的那样)。我没能找到任何说明len()自动添加空格的东西,所以我得出的结论是,它必须是逗号如何与len()函数相互作用,但我对如何或为什么感到困惑?

my_dict={
"name":"troy aikman",
"position":"qb",
"team":"dalls cowboys",
"age": 54,
"weight": 220.,
"superbowls":["XXVII","XXVIII","XXX"],
"awards":{
"super_bowl_mvp":"XXVII",
"probowl":[1991,1992,1993,1994,1995,1996],
"man_of_the_year":1997
}
}
print(
my_dict['name'] + " has won", len(my_dict['superbowls'])
)

在Python中,print函数打印指定的每个参数,由分隔符sep分隔。sep的默认值是一个空格。

传递两个参数:

1:my_dict['name'] + " has won"(求值为"troy aikman has won")

2:len(my_dict['superbowls'])(求值为数字3,其字符串表示为"3")

输出的是第一个参数("troy aikman has won");sep值(一个空格);第二个参数("3"): "troy aikman赢了">

Doc at https://docs.python.org/3/library/functions.html#print

  • 在字符串组合中使用f-string比使用+,更好。

例子
my_dict={
"name":"troy aikman",
"position":"qb",
"team":"dalls cowboys",
"age": 54,
"weight": 220.,
"superbowls":["XXVII","XXVIII","XXX"],
"awards":{
"super_bowl_mvp":"XXVII",
"probowl":[1991,1992,1993,1994,1995,1996],
"man_of_the_year":1997
}
}
print(f"{my_dict['name']} has won{len(my_dict['superbowls'])}")
结果

troy aikman has won3

您正在使用print语句打印用逗号分隔的两个不同的值。默认有一个空格

print(
my_dict['name'] + " has won", len(my_dict['superbowls'])
)

如果你想要troy aikman has won3这个,然后连接两个值(都必须是str形式)

print(
my_dict['name'] + " has won"+str(len(my_dict['superbowls'])
))

相关内容

  • 没有找到相关文章