Strings in Python

Strings are one of the most important and commonly used data types of Python. They are used when you need to store a word or sentence in a variable. Python treats anything written in single or double quotes as a string. Following code initializes two strings in Python:

str1 = “This is string one.”
str2 = “Another one.”

Multiline Strings

There are many instances where you need to stores a paragraph in a variable but if your next goes to the next line Python will throw an EOL (End Of Line) error and will not be able to recognize it as a string. That’s when you use triple quotes.

paragraph = “““ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ”””

Indexing Strings

Strings can be indexed just like arrays in Python. You can access dffferent characters of a string using square brackets [].

str1 = “This is string one.”

Upon executing this code, the following will be displayed:


Slicing Strings

You can access a range of characters from a String using square brackets too.


Updating Strings

To change the value of a string, you can simply reassign another value to the same variable or concatenating it with a part of it.

str1 = “This is string one.”
str1 = “This is modified string.”

print(str1[8:16] + “ meaning.”)
This is modified string.
modified meaning

String Format

To print numerals inside strings, we can use format() method. The method is applied on a formatted string variable and takes the variables or values to be put in the placeholder {}.

age = 18
txt = "My name is Ali and I am {} years old"
My name is Ali and I am 18 years old

You can also use index numbers inside placeholders to put different variables at different places.

birthYear = 1999
schoolYear = 2005
graduate = 2020

profile = "I was born in {1}, went to school in {0}, and graduated in {2}."
print(profile.format(schoolYear, birthYear, graduate))
I was born in 1999, went to school in 2005, and graduated in 2020.

Escape Characters

To insert non-printable characters other than numerical that are illegal in a String or which are used for some other purpose in Python, we use the escape character. It is denoted by a backslash “\” followed by the character you want to insert.

print(“My favourite movie is \”Lord of The Rings\””)
My favourite movie is “Lord of The Rings”

Following are some commonly used escape character code:

\’Single Quote
\nNew Line
\rCarriage Return
\fForm Feed

String Operators

Python provides a number of string operators to manipulate strings. Some of the major ones are as given below.

Note: Let’s assume a = “Hello” and b = “World” for examples.

+ConcatenationAdds values on either side of the operatora + b will give HelloWorld
*RepetitionRepeats the same string specified number of timesa*2 will give HelloHello
inMembership Returns true if a character exists in the given string(H in a) will give 1
not inMembership Returns true if a character does not exist in the given string(t not in a) will give 1

Built-in Functions

capitalize()Converts the first character to upper case
lower()Converts string into lower case
upper()Converts string into upper case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
strip()Removes both the starting and ending spaces


I am a Software Engineer with ample experience in making games, websites, mobile apps and augmented reality solutions.

Pin It on Pinterest