Python Strings

What are strings?

In Python, anything that you enclose between single or double quotation marks is considered a string. A string is essentially a sequence or array of textual data. Strings are used when working with Unicode characters.

Example:

location = "Nepal"
print("Welcome to " + location)

Output

Welcome to Nepal

Note: It does not matter whether you enclose your strings in single or double quotes; the output remains the same. Sometimes, the user might need to put quotation marks in between the strings. For example, consider the sentence: He said, “I want to explore Ashlya”.

How will you print this statement in Python?

Wrong way ❌

print("He said, "I want to explore Ashlya".")

Output :

SyntaxError: invalid syntax

Right way ✔️

print('He said, "I want to explore Ashlya".')
# OR
print("He said, \"I want to explore Ashlya\".")

Output :

He said, "I want to explore Ashlya".

What if you want to write multiline strings?

Sometimes the programmer might want to include a note, a set of instructions, or simply explain a piece of code. While this can be done using multiline comments, the programmer may want to display this in the program's output. This is done using multiline strings.

Example:

recipe = """
1. Start with the scenic views of Pokhara, known for its stunning lakes and the Annapurna range.
2. Add a pinch of spice from the streets of Bhaktapur, famous for its 'King Curd' (juju dhau).
3. Stir in the flavors of Kathmandu, where you can find delicious 'Daal Bhat' and vibrant markets.
4. Incorporate the rich cultural heritage of Lumbini, the birthplace of Lord Buddha, known for its serene gardens.
5. Finish with the traditional dishes of Janakpur, famous for its 'Mithila' paintings and 'Dahi-Chura'.
"""
print(recipe)

note = '''
This is a multiline string.
It highlights some of the beautiful cities in Nepal and their unique culinary delights.
'''
print(note)

Output:

1. Start with the scenic views of Pokhara, known for its stunning lakes and the Annapurna range.
2. Add a pinch of spice from the streets of Bhaktapur, famous for its 'King Curd' (juju dhau).
3. Stir in the flavors of Kathmandu, where you can find delicious 'Daal Bhat' and vibrant markets.
4. Incorporate the rich cultural heritage of Lumbini, the birthplace of Lord Buddha, known for its serene gardens.
5. Finish with the traditional dishes of Janakpur, famous for its 'Mithila' paintings and 'Dahi-Chura'.

This is a multiline string.
It highlights some of the beautiful cities in Nepal and their unique culinary delights.