Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String Concatenation - concatenating '\n'

I am new to Python and need help trying to understand two problems i am getting relating to concatenating strings. I am aware that strings can be added to concatenate each other using + symbol like so.

>>> 'a' + 'b'
'ab'

However, i just recently found out you do not even need to use the + symbol to concatenate strings (by accident/fiddling around), which leads to my first problem to understand - How/why is this possible!?

>>> print 'a' + 'b'
ab

Furthermore, I also understand that the '\n' string produces a 'newline'. But when used in conjunction with my first problem. I get the following.

>>> print '\n' 'a'*7

a
a
a
a
a
a
a

So my second problem arises - "Why do i get 7 new lines of the letter 'a'. In other words, shouldn't the repeater symbol, *, repeat the letter 'a' 7 times!? As follows.

>>> print 'a'*7
aaaaaaa

Please help me clarify what is going on.

like image 368
Abraham Avatar asked Jul 23 '11 11:07

Abraham


People also ask

How do you concatenate 4 variables in Python?

Concatenate multiple strings The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator. However, there's another method that allows an easy way of concatenating multiple strings. It is using the in-place (+=) operator.

How do you concatenate 3 strings in Python?

Concatenation means joining strings together end-to-end to create a new string. To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

What is the best way to concatenate strings in Python?

One of the most popular methods to concatenate two strings in Python (or more) is using the + operator. The + operator, when used with two strings, concatenates the strings together to form one.


1 Answers

When "a" "b" is turned into "ab", this ins't the same as concatenating the strings with +. When the Python source code is being read, adjacent strings are automatically joined for convenience.

This isn't a normal operation, which is why it isn't following the order of operations you expect for + and *.

print '\n' 'a'*7

is actually interpreted the same as

print '\na'*7

and not as

print '\n' + 'a'*7
like image 152
Jeremy Avatar answered Sep 30 '22 06:09

Jeremy