Does the spacing at the beginning and end of a string matter?

Question

Does the spacing at the beginning and end of a string matter?

Answer

Yes! Any characters you put in a string will be displayed, and space is a character just like any other. If you try putting more spaces after the word Spam, for example, you’ll see that amount of spacing printed out when you run it. This is important to note because Codecademy checks for exactly what is mentioned in the instructions on any given exercise, including spacing, capitalization, spelling, and punctuation.

3 Likes

does it matter on which string i put the space? for example in the Spam and eggs string does it matter if i put “Spam(space)” "and(space) " “eggs” compared to if i were to put “Spam” “(space) and” “(space)eggs” ?

6 Likes

No this does not matter, as long as the space is there on the right or the left of the “+”, don’t be afraid to experiment with it and have fun!

3 Likes

I have a question. why do we use the + in between instead of just leaving them out? Either way it print out the same.

3 Likes

Of course you can simply write the following and achieve the same

print “Spam and eggs”

But that’s not the point of the exercise is it? In real-world application, you don’t always get to print a simple string. As simple as, say, an “age calculator”; when you need to print the result “You are x years of age.” you’ll need to concatenate.

print “You are " + str(user_age) + " years of age.”

6 Likes

I believe aljorpp’s question was why use + operator in: "Spam "+"and "+“eggs”
when we could write: "Spam ""and "“eggs”
and get the same result in the console after applying print.

And as I posted this comment, I understood your asnwer :blush: (first think, then speak)

4 Likes

By that logic you could simply state print("Spam and eggs"). First think, then speak :blush:.

2 Likes

Hi, this helps a lot thanks because I wasn’t sure before!

does access by index also consider space as a character

Yes, a space is a character (ordinal 32, hex 20) so does count in the length of a string as it occupies one position in the string.

1 Like

Extending this question a little more, and I share with the most of reply above, but I would dare to ask this question in another way: Does the spaces (as many as there are) around the operator matter? With no space does it work the same? What does the sysntax say? Maybe these spaces are due to let the code line more clear or in a didactic way, isn´t it?

Spaces around operators have no effect, and yes, it makes the code more readable. In Python, leading spaces are treated as block indents so there should be no leading spaces unless it is intentionally creating a block.

1 Like

Ok! That´s it. Thank you. :wink:

1 Like