Python Strings

String is a sequence of characters enclosed by quotation marks : it can be any type either a single quotation mark or double quotation mark or it can be a triple quotation mark.

Let us see how we can define strings in python :

x='hello codiens'
y="hello codiens"
z='''hello codiens'''
v="""hello codiens"""
print(type(x))
print(type(y))
print(type(z))
print(type(v))

The output of the following code will be -

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

Multiline Strings

We can not define multiline strings enclosed by single or double quotation marks. If we do this then it will raise an error.

Multiline strings are defined by three quotation marks in python.

Let us understand this, how it works -

code="""Hello Codiens, your code is
bug free"""
pro='''Python strings
are interesting'''
print(type(code))
print(type(pro))
print(code)
print(pro)

The resulting output of the following program will be -

<class 'str'>
<class 'str'>
Hello Codiens, your code is
bug free
Python strings
are interesting

Python String Memory management

Python Strings operate in the same manner as C character arrays - a Sequence of characters.

Let us understand this more clearly through an example -

x='codiens'

This will be stored in memory in the form of sequential slicing, which means each character has a unique memory location/index. Python strings are arrays of bytes representing unicode characters.

how python string stored in memory.

In the above sequence, x[0] has ‘c’ and x[1] has ‘o’ and so on

x='codiens'
print(x[0])
print(x[2])
print(x[1])
print(x[5])

Then, the output of the following code will be -

Negative Indexing of Python String

how python string stored in memory.

As we can see in the above, python string follows negative indexing as well. It starts from the end of the string.

x='codiens'
print(x[-1])
print(x[-6])
print(x[-3])
print(x[-5])

The output of the following program will be -

s
o
e
d