Can we perform the same operations on multi-line strings that we perform on other strings?

Question

Can we perform the same operations on multi-line strings that we perform on other strings?

Answer

Yes, operations like concatenation can be performed to combine multi-line strings with single-line strings because strings created using the two techniques are both actually of the same type.

Representing String Literals in Python

In Python, a variety of techniques can be used to represent string literals in code. Each technique offers particular advantages, but all of the techniques create the same type, namely a string. Since they all create the same type of string object, concatenation can be used to combine two strings, regardless of whether they were created using different techniques.

Technique Reasons for Using It
Double quote delimiter Can include single quotes in the string without using an escape sequence
Single quote delimiter Can include double quotes in the string without using an escape sequence
Raw string Can include literal escape sequences in the string
Triple double quote delimiter Can include multiple lines in the string without using an escape sequence
Triple single quote delimiter Can include multiple lines in the string without using an escape sequence

Credit for this post goes to @appylpye. We hope this helps.

Hello, sir.
Would you be so kind to provide examples to this?
Thank you in advance.

3 Likes

I agree that examples will be helpful.

Here is a concatenation multi-line example where two long multi line strings from a poem are added together.

first_Multi_Line_String = """Had I the heaven's embroidered cloths,
Enwrought with golden and silver light,
The blue and the dim and the dark cloths 
Of night and light and the half-light;
I would spread the cloths under your feet"""

second_Multi_Line_String = """ But I, being poor, have only my dreams;
I have spread my dreams under your feet;
Tread softly because you tread on my dreams."""

print(first_Multi_Line_String + second_Multi_Line_String)

##RESULT:

Had I the heaven’s embroidered cloths,
Enwrought with golden and silver light,
The blue and the dim and the dark cloths
Of night and light and the half-light;
I would spread the cloths under your feet
But I, being poor, have only my dreams;
I have spread my dreams under your feet;
Tread softly because you tread on my dreams.

10 Likes
test = "bsh   

nd"

test_1 = 'haj 

sn'

test_2 = """hkjav

lk  jf"""

When printing the three variable out, the previous output incurred an EOL error except the last one.

Hello, I have a question about quotation usage. Please see the above example. So does that mean only triple quotation marks can be used for multi-lines comments?

1 Like

Yes, only triple quotation marks can create multi-lines comments.

2 Likes