Overview of Strings¶
Let us get an overview of how strings are used in Python.* str
is the class or type to represent a string.
- A string is nothing but list of characters.
- Python provides robust set of functions as part of
str
to manipulate strings. - As
str
object is nothing but list of characters, we can also use standard functions available on top of Python collections such aslist
,set
etc.
{note}
We have covered lists quite extensively in subsequent sections. Once you go through the lists, perform some of the operations on top of strings. Here are few examples.
In [1]:
s = 'Hello World'
In [2]:
type(s)
Out[2]:
str
In [3]:
print(s)
Hello World
In [4]:
s[:5]
Out[4]:
'Hello'
In [5]:
s[-5:]
Out[5]:
'World'
In [6]:
len(s)
Out[6]:
11
In [7]:
sorted(s)
Out[7]:
[' ', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']
- String in Python can be represented in different ways
- Enclosed in single quotes –
'ITVersity"s World'
- Enclosed in double quotes –
"ITVersity's World"
- Enclosed in triple single quotes –
'''ITVersity"s World'''
- Enclosed in triple double quotes –
"""ITVersity's World"""
- Enclosed in single quotes –
- If your string itself have single quote, enclose the whole string in double quote.
- If your string itself have double quote, enclose the whole string in single quote.
- Triple single quotes or triple double quotes can be used for multi line strings
In [8]:
s = 'Hello World'
s
Out[8]:
'Hello World'
In [9]:
s = "Hello World"
s
Out[9]:
'Hello World'
In [10]:
s = 'ITVersity"s World'
s
Out[10]:
'ITVersity"s World'
In [11]:
s = "ITVersity's World"
s
Out[11]:
"ITVersity's World"
In [12]:
s = '''ITVersity's World'''
s
Out[12]:
"ITVersity's World"
In [13]:
s = '''ITVersity's
World'''
s
Out[13]:
"ITVersity's \nWorld"