Home > Back-end >  Unexpected space in outcome when combining len() to a string in python
Unexpected space in outcome when combining len() to a string in python

Time:10-08

new programming student here! I don't understand why this code returns "troy aikman has won 3" instead of "troy aikman has won3". There is no space after " has won" so I'm assuming it has to do with the ", len()" portion. I've switched the comma to " " which gave me an error (as I thought it would). I haven't been able to find anything stating that len() automatically adds spaces so I've concluded that it has to be how the comma interacts with the len() function, but am confused as to how or why?

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'])
)

CodePudding user response:

In Python, the print function prints each of the arguments specified, separated by a separator sep. The default value for sep is a space.

You are passing two arguments:

1: my_dict['name'] " has won" (which evaluates to "troy aikman has won")

2: len(my_dict['superbowls']) (which evaluates to "3")

So what prints is the first argument; the sep value (a space); and "3": "troy aikman has won 3"

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

CodePudding user response:

  • use f-string is a better way than use and , in string combination.

example

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'])}")

result

troy aikman has won3

CodePudding user response:

You are using print statement printing two different values separated by commas. So by default there is a space

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

If you want troy aikman has won3 this then concatenate both values(both must in str form)

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