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 as list, 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.

s = 'Hello World'
type(s)
str
print(s)
Hello World
s[:5]
'Hello'
s[-5:]
'World'
len(s)
11
sorted(s)
[' ', '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"""

  • 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

s = 'Hello World'
s
'Hello World'
s = "Hello World"
s
'Hello World'
s = 'ITVersity"s World'
s
'ITVersity"s World'
s = "ITVersity's World"
s
"ITVersity's World"
s = '''ITVersity's World'''
s
"ITVersity's World"
s = '''ITVersity's 
World'''
s
"ITVersity's \nWorld"