Python String

What are Strings?

Strings are an ordered collection or sequence of characters. They are used to store information in the form of text. Strings are immutable in Python. Once a String is assigned a value, its value cannot be modified (It can be reassigned or completely deleted).

How to create strings in Python?

Strings are created using quotations in Python. Single, Double or Triple quotes can be used to denote a string in Python code. A simple python string can be created

			

my_var = 'hello'    #String Literal using single quotes
#or
my_var = "hello"    #String Literal using double quotes

				

The key difference between declaring a string literal using single or double quotes is that with single quotes, the usage of the double quotes is allowed inside the single quotes.

For example, with single quotes, you can write something

			

my_var = 'Elon Musk just tweeted that "Been spending most of our lives living in the past time paradise!""'
print(my_var)

				

Output:

Elon Musk just tweeted that "Been spending most of our lives living in the past time paradise!"

If you use double quotes instead,

			

my_var = "Elon Musk just tweeted that "Been spending most of our lives living in the past time paradise!""
print(my_var)

				

Output:

SyntaxError: invalid syntax

If we want to use both the single and double quotes in a string, we make use of the triple quotes.

			

my_var = '''
'Elon Musk just tweeted that'
"Been spending most of our lives living in the past time paradise"
'''
print(my_var)

				

Output:

'Elon Musk just tweeted that' "Been spending most of our lives living in the past time paradise"

As you can see in the above example, we can also use triple quotes to write multiline string literals.

If you want to write multiline strings in the code but only want the output to be in a single line, you can use "\" at the end of each line.

			

my_var = '''\
'Elon Musk just tweeted that \
"Been spending most of our lives living in the past time paradise"'\
'''
print(my_var)

				

Output:

'Elon Musk just tweeted that "Been spending most of our lives living in the past time paradise!"'

"\" also works with single quotes and double quotes.

Accessing strings in Python

We can access an element in a string by using the index of that element. We put the index inside the [] parentheses.

			

sampleString = "Hello This is Joey from Arizona"
print(sampleString[7])     #accessing 7th index element
print(sampleString[12])    #accessing 12th index element
print(sampleString[-3])    #accessing 3rd index element from the end
print(sampleString[-10])   #accessing 10th index element from the end
print(sampleString[:10])   #accessing first 10 elements using slicing
print(sampleString[6:])    #accessing all the elements after starting from the 6th index
print(sampleString[-5:])   #accessing all the elements starting from 5th index element from the end
print(sampleString[1::2])  #accessing all the elements starting from the 1st index with increment of 2

				

Output:

h s o o Hello This This is Joey from Arizona izona el hsi oyfo rzn

As you can see in the above code snippet, we can also use negative indices to access elements by referring to them with respect to the end of the string. Similarly, slicing also works with strings just like any other sequence in Python.

As mentioned above already, Python strings are immutable. You can not append a String or delete a particular element from a String. Instead, you can delete the whole String using the del keyword or reassign it with a different value.

			

sampleString = "Hello This is Joey from Arizona"
del sampleString
print(sampleString)

				

Output:

NameError: name 'sampleString' is not defined

Operations on Strings

Concatenation of Strings

Multiple strings can be combined to create a new string as a result. We can do concatenation in Python using the + operator.

			

sampleString1 = "Hello "
sampleString2 = "This is Joey "
sampleString3 = "from Arizona"
sampleString4 = sampleString1 + sampleString2 + sampleString3
print(sampleString4)
print("A" + "B" + "C")

				

Output:

Hello This is Joey from Arizona ABC

Repeating a string multiple times

The * operator is used to multiply a string with a integer value to repeat it a specified number of times.

			

sampleString1 = "Hello "
sampleString2 = sampleString1*3
print(sampleString4)

				

Output:

Hello Hello Hello

Iterating over a string

Since String is a sequence type in Python, we can use loops to iterate through its elements.

			

sampleString1 = "Hello "
for character in sampleString1:
    print(character)

				

Output:

H e l l o

Escape Sequences

Escape sequences allow the programmer to use special characters in a string. For example, if you want to use single quotes inside a string that is being denoted with single quotes, need the escape sequences to represent the inner single quotes. An escape sequence is denoted using the backslash "\"inside the string.

			

sampleString1 = '\'This is Joey\''
print(sampleString1)

				

Output:

'This is Joey'

Other available escape sequences in Python:

Escape Sequence Description
\\ Backslash
\’ Single quote
\" Double quote
\a ASCII bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII LineFeed
\r ASCII Carriage Return
\t ASCII Tab (Horizontal)
\v ASCII Tab (Vertical)
\ Newline ignore
\ooo Octal value
\xHH Hexadecimal Value

Methods available methods for strings in Python are :

Method Description
capitalize Return the string with all characters capitalized
casefold Return a string for caseless comaprision
center Return a centered string
count Return the number of occurrences of an element
encode Encode the string with a specified encoding
endswith Return True if the string ends with a given suffix Else return false
find Return the first index of a given substring inside a string Return -1 on failure
format Return a substituted version of the string using substitutions from argos and kwargs
index Return the first index of a given substring inside a string Raises error on failure
isalnum Return True if the string is alpha-numeric Else return False