Facebook Pixel

Strings

What are strings?

In Python, anything enclosed within single or double quotation marks is considered a string. A string is essentially a sequence of characters.

Strings are used when working with Unicode characters.

Example:

name = "Samuel"
print("Hello, " + name)

Output:

Hello, Samuel

Note: It does not matter whether you enclose your strings in single or double quotes, the output remains the same.

Sometimes, you may need to include quotation marks inside a string. For example: He said, “I want to eat an apple.”

How will you print this statement in python?

❌ Wrong way

print("He said, "I want to eat an apple".")

Output:

print("He said, "I want to eat an apple".")
                     ^
SyntaxError: invalid syntax

✔️ Right way

print('He said, "I want to eat an apple".')
#OR
print("He said, \"I want to eat an apple\".")

Output:

He said, "I want to eat an apple".
He said, "I want to eat an apple".

What if you want to write multiline strings?

Sometimes the programmer might want to include a note, or a set of instructions, or just might want to explain a piece of code. Although this might be done using multiline comments, the programmer may want to display this in the execution of programmer. This is done using multiline strings.

Example:

recipe = """
1. Heat the pan and add oil
2. Crack the egg
3. Add salt in egg and mix well
4. Pour the mixture in pan
5. Fry on medium heat
"""
print(receipe)
 
note = '''
This is a multiline string
It is used to display multiline message in the program
'''
print(note)

Output:

1. Heat the pan and add oil
2. Crack the egg
3. Add salt in egg and mix well
4. Pour the mixture in pan
5. Fry on medium heat


This is a multiline string
It is used to display multiline messages in the program