Python Strings

 

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:

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

Output:

Hello, Maxon

 

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. Example, consider the sentence: 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:

receipe = """
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 message in the program