0% found this document useful (0 votes)
15 views29 pages

Python Unit 2

Uploaded by

kacavic653
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views29 pages

Python Unit 2

Uploaded by

kacavic653
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

B.

TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

UNIT – III: Data Structures


 Lists
 Tuples
 Sets
 Dictionaries
 Sequences

Python List

You'll learn everything about Python lists; how they are created, slicing of a list, adding or
removing elements from them and so on.

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

 Also, a list can even have another list as an item. This is called nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?

 There are various ways in which we can access the elements of a list.

P. Veera Prakash 1|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
List Index:

 We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
 Trying to access an element other that, this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.
 Nested list are accessed using nested indexing.

Negative indexing:

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.

How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

P. Veera Prakash 2|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need two index that will slice that portion from the list.

How to change or add elements to a list?

 List are mutable, meaning, their elements can be changed unlike string or tuple.
 We can use assignment operator (=) to change an item or a range of items.

We can add one item to a list using append() method or add several items using extend() method.

 We can also use + operator to combine two lists. This is also called concatenation.
 The * operator repeats a list for the given number of times.

Furthermore, we can insert one item at a desired location by using the method insert ( ) or insert
multiple items by squeezing it into an empty slice of a list.

P. Veera Prakash 3|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

How to delete or remove elements from a list?

We can delete one or more items from a list using the keyword del. It can even delete the list
entirely.

We can use remove() method to remove the given item or pop() method to remove an item
at the given index.
 The pop() method removes and returns the last item if index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
 We can also use the clear( ) method to empty a list.

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

>>> my_list = ['p','r','o','b','l','e','m']


>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Methods

 Methods that are available with list object in Python programming are tabulated below.

P. Veera Prakash 4|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
 They are accessed as list.method ( ). Some of the methods have already been used above.

Python List Methods


append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list

Some examples of Python list methods:

List Comprehension: Elegant way to create new List

 List comprehension is an elegant and concise way to create new list from an existing list in
Python.
 List comprehension consists of an expression followed by for statement inside square
brackets.

Here is an example to make a list with each item being increasing power of 2.

Other List Operations in Python


P. Veera Prakash 5|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

List Membership Test

We can test if an item exists in a list or not, using the keyword in.

Built-in Functions with List

Built-in functions like all( ), any( ), enumerate( ), len( ), max( ), min( ), list( ), sorted( ) etc. are
commonly used with list to perform different tasks.

Function Description
all() Return True if all elements of the list are true (or if the list is empty).
any() Return True if any element of the list is true. If the list is empty, return False.
Return an enumerate object. It contains the index and value of all the items of list
enumerate()
as a tuple.
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
sorted() Return a new sorted list (does not sort the list itself).
sum() Return the sum of all elements in the list.

Python Tuple
You'll learn everything about Python tuples. More specifically, what are tuples, how to create
them, when to use them and various methods you should be familiar with.

In Python programming, a tuple is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas in a list, elements can be
changed.

Advantages of Tuple over List

Since, tuples are quite similar to lists, both of them are used in similar situations as well.

However, there are certain advantages of implementing a tuple over a list. Below listed are some
of the main advantages:
P. Veera Prakash 6|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
 We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary. With list, this
is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.

Creating a Tuple

 A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma. The parentheses are optional but it is a good practice to write it.
 A tuple can have any number of items and they may be of different types (integer, float,
list, string etc.).

Creating a tuple with one element is a bit tricky.

Having one element within parentheses is not enough. We will need a trailing comma to indicate
that it is in fact a tuple.

P. Veera Prakash 7|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Accessing Elements in a Tuple

There are various ways in which we can access the elements of a tuple.

1. Indexing

We can use the index operator [] to access an item in a tuple where the index starts from 0.

So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that
(6, 7,...) will raise an IndexError.

The index must be an integer, so we cannot use float or other types. This will result into
TypeError.

Likewise, nested tuple are accessed using nested indexing, as shown in the example below.

2. Negative Indexing

 Python allows negative indexing for its sequences.


 The index of -1 refers to the last item, -2 to the second last item and so on.

P. Veera Prakash 8|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
3. Slicing

We can access a range of items in a tuple by using the slicing operator - colon ":".

Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need the index that will slice the portion from the tuple.

Changing a Tuple

 Unlike lists, tuples are immutable.


 This means that elements of a tuple cannot be changed once it has been assigned. But, if the
element is itself a mutable datatype like list, its nested items can be changed.
 We can also assign a tuple to different values (reassignment).

 We can use + operator to combine two tuples. This is also called concatenation.
 We can also repeat the elements in a tuple for a given number of times using the *
operator.
 Both + and * operations result into a new tuple.

P. Veera Prakash 9|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Deleting a Tuple

As discussed above, we cannot change the elements in a tuple. That also means we cannot delete
or remove items from a tuple.

But deleting a tuple entirely is possible using the keyword del.

Python Tuple Methods

Methods that add items or remove items are not available with tuple. Only the following two
methods are available.

Python Tuple Method

Method Description

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

Some examples of Python tuple methods:

P. Veera Prakash 10 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Built-in Functions with Tuple

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), tuple() etc. are
commonly used with tuple to perform different tasks.

Function Description
all() Return True if all elements of the tuple are true (or if the tuple is empty).
Return True if any element of the tuple is true. If the tuple is empty, return
any()
False.
Return an enumerate object. It contains the index and value of all the
enumerate()
items of tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
Take elements in the tuple and return a new sorted list (does not sort the
sorted()
tuple itself).
sum() Retrun the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

Python Sets

You'll learn everything about Python sets; how they are created, adding or removing elements
from them, and all operations performed on sets in Python.

A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).

However, the set itself is mutable. We can add or remove items from it.

Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.

How to create a set?

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().

It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.

P. Veera Prakash 11 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Try the following examples as well.

Creating an empty set is a bit


tricky.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements we use the set() function without any argument.

How to change a set in Python?

 Sets are mutable. But since they are unordered, indexing have no meaning.
 We cannot access or change an element of set using indexing or slicing. Set does not
support it.

P. Veera Prakash 12 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

 We can add single element using the add() method and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.

P. Veera Prakash 13 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

How to remove elements from a set?


A particular item can be removed from set using methods, discard() and remove().

The only difference between the two is that, while using discard() if the item does not exist in
the set, it remains unchanged. But remove() will raise an error in such condition.

The following example will illustrate this.

 Similarly, we can remove and return an item using the pop() method.
 Set being unordered, there is no way of determining which item will be popped. It is
completely arbitrary.
 We can also remove all items from a set using clear().

Python Set Operations

Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.

P. Veera Prakash 14 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

Set Union

 Union of A and B is a set of all elements from both sets.


 Union is performed using | operator. Same can be accomplished using the method
.union().

Try the following examples on Python shell.

# use union function


>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection

 Intersection of A and B is a set of elements that are common in both sets.


 Intersection is performed using & operator. Same can be accomplished using the method
intersection().

Try the following examples on Python shell.

# use intersection function on A

P. Veera Prakash 15 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Set Difference

 Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly,
B - A is a set of element in B but not in A.
 Difference is performed using - operator. Same can be accomplished using the method
difference().

Try the following examples on Python shell.

# use difference function on A


>>> A.difference(B)
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
# use difference function on B
>>> B.difference(A)
{8, 6, 7}

Set Symmetric Difference

 Symmetric Difference of A and B is a set of elements in both A and B except those that are
common in both.
 Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().

Try the following examples on Python shell.

# use symmetric_difference function on A


>>> A.symmetric_difference(B)

P. Veera Prakash 16 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

Different Python Set Methods

There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with set objects.

Method Description
add() Add an element to a set
clear() Remove all elements form a set
copy() Return a shallow copy of a set
difference() Return the difference of two or more sets as a new set
difference_update() Remove all elements of another set from this set
Remove an element from set if it is a member. (Do nothing if the
discard()
element is not in set)
intersection() Return the intersection of two sets as a new set
intersection_update() Update the set with the intersection of itself and another
isdisjoint() Return True if two sets have a null intersection
issubset() Return True if another set contains this set
issuperset() Return True if this set contains another set
Remove and return an arbitary set element. Raise KeyError if the
pop()
set is empty
Remove an element from a set. If the element is not a member,
remove()
raise a KeyError
symmetric_difference() Return the symmetric difference of two sets as a new set
symmetric_difference_update() Update a set with the symmetric difference of itself and another
union() Return the union of sets in a new set
update() Update a set with the union of itself and others

P. Veera Prakash 17 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc.
are commonly used with set to perform different tasks.

Function Description
all() Return True if all elements of the set are true (or if the set is empty).
any() Return True if any element of the set is true. If the set is empty, return False.
Return an enumerate object. It contains the index and value of all the items of set
enumerate()d
as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
sum() Retrun the sum of all elements in the set.

Python Frozenset

 Frozenset is a new class that has the characteristics of a set, but its elements cannot be
changed once assigned. While tuples are immutable lists, frozensets are immutable sets.
 Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other
hand, frozensets are hashable and can be used as keys to a dictionary.
 Frozensets can be created using the function frozenset().
 This datatype supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not
have method that add or remove elements.

# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

Try these examples on Python shell.

>>> A.isdisjoint(B)
P. Veera Prakash 18 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'

Python Dictionary

 You'll learn everything about Python dictionary; how they are created, accessing, adding
and removing elements from them and, various built-in methods.
 Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.
 Dictionaries are optimized to retrieve values when the key is known.

How to create a dictionary?

 Creating a dictionary is as simple as placing items inside curly braces {} separated by


comma.
 An item has a key and the corresponding value expressed as a pair, key: value.
 While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

As you can see above, we can also create a dictionary using the built-in function dict().

How to access elements from a dictionary?

While indexing is used with other container types to access values, dictionary uses keys. Key can
be used either inside square brackets or with the get() method.
P. Veera Prakash 19 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.

How to change or add elements in a dictionary?

Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.

If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.

How to delete or remove elements from a dictionary?

We can remove a particular item in a dictionary by using the method pop(). This method removes
as item with the provided key and returns the value.

The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary itself.

P. Veera Prakash 20 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Python Dictionary Methods

Methods that are available with dictionary are tabulated below. Some of them have already been
used in the above examples.

Method Description

clear() Remove all items form the dictionary.


copy() Return a shallow copy of the dictionary.
fromkeys(seq[, Return a new dictionary with keys from seq and value equal to v (defaults to
v]) None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not found. If d is not
pop(key[,d])
provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value of d
setdefault(key[,d])
and return d (defaults to None).
Update the dictionary with the key/value pairs from other, overwriting existing
update([other])
keys.
values() Return a new view of the dictionary's values

P. Veera Prakash 21 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Here are a few example use of these methods.

Python Dictionary Comprehension

 Dictionary comprehension is an elegant and concise way to create new dictionary from an
iterable in Python.
 Dictionary comprehension consists of an expression pair (key: value) followed by for
statement inside curly braces {}.
 Here is an example to make a dictionary with each item being a pair of a number and its
square.

squares = {x: x*x for x in range(6)}

# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


print(squares)

This code is equivalent to

squares = {}
for x in range(6):
squares[x] = x*x

 A dictionary comprehension can optionally contain more for or if statements.


 An optional if statement can filter out items to form the new dictionary.
 Here are some examples to make dictionary with only odd items.

odd_squares = {x: x*x for x in range(11) if x%2 == 1}


# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(odd_squares)

Built-in Functions with Dictionary

Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with dictionary to
perform different tasks.

Function Description

all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
P. Veera Prakash 22 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

len() Return the length (the number of items) in the dictionary.


cmp() Compares items of two dictionaries.

sorted() Return a new sorted list of keys in the dictionary.

Here are some examples that uses built-in functions to work with dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))

Python Strings

 A string is a sequence of characters.


 A character is simply a symbol. For example, the English language has 26 characters.
 Computers do not deal with characters, they deal with numbers (binary). Even though you
may see characters on your screen, internally it is stored and manipulated as a combination
of 0's and 1's.
 This conversion of character to a number is called encoding, and the reverse process is
decoding. ASCII and Unicode are some of the popular encoding used.
 In Python, string is a sequence of Unicode character. Unicode was introduced to include
every character in all languages and bring uniformity in encoding. You can learn more
about Unicode from here.

How to create a string?


Strings can be created by enclosing characters inside a single quote or double quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.

P. Veera Prakash 23 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

How to access characters in a string?


 We can access individual characters using indexing and a range of characters using slicing.
Index starts from 0. Trying to access a character out of index range will raise an
IndexError. The index must be an integer. We can't use float or other types, this will
result into TypeError.
 Python allows negative indexing for its sequences.
 The index of -1 refers to the last item, -2 to the second last item and so on. We can access a
range of items in a string by using the slicing operator (colon).

If we try to access index out of the range or use decimal number, we will get errors.

# index must be in range


>>> my_string[15]
...
IndexError: string index out of range

# index must be an integer


>>> my_string[1.5]
...
TypeError: string indices must be integers

Slicing can be best visualized by considering the index to be between the elements as shown
below.

If we want to access a range, we need the index that will slice the portion from the string.

How to change or delete a string?


Strings are immutable. This means that elements of a string cannot be changed once it has been
assigned. We can simply reassign different strings to the same name.
P. Veera Prakash 24 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
>>> my_string = 'programiz'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'

We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the keyword del.

>>> del my_string[1]


...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined

Python String Operations


There are many operations that can be performed with string which makes it one of the most used
datatypes in Python.

Concatenation of Two or More Strings

 Joining of two or more strings into a single one is called concatenation.


 The + operator does this in Python. Simply writing two string literals together also
concatenates them.
 The * operator can be used to repeat the string for a given number of times.
 Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

>>> # two string literals together


>>> 'Hello ''World!'
'Hello World!'

>>> # using parentheses


>>> s = ('Hello '
... 'World')
>>> s
'Hello World'

P. Veera Prakash 25 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Built-in functions to Work with Python

 Various built-in functions that work with sequence, works with string as well.
 Some of the commonly used ones are enumerate() and len(). The enumerate() function
returns an enumerate object. It contains the index and value of all the items in the string as
pairs. This can be useful for iteration.
 Similarly, len() returns the length (number of characters) of the string.

Python String Formatting

Escape Sequence

If we want to print a text like -He said, "What's there?"- we can neither use single quote or double
quotes. This will result into SyntaxError as the text itself contains both single and double quotes.

>>> print("He said, "What's there?"")


...
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
...
SyntaxError: invalid syntax

One way to get around this problem is to use triple quotes. Alternatively, we can use escape
sequences.

An escape sequence starts with a backslash and is interpreted differently. If we use single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with
double quotes. Here is how it can be done to represent the above text.

P. Veera Prakash 26 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Here is a list of all the escape sequence supported by Python.

Escape Sequence Description


\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
Here are some examples

>>> print("C:\\Python32\\Lib")
C:\Python32\Lib

>>> print("This is printed\nin two lines")


This is printed
in two lines

>>> print("This is \x48\x45\x58 representation")


This is HEX representation

Raw String to ignore escape sequence

Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r
or R in front of the string. This will imply that it is a raw string and any escape sequence inside it
will be ignored.

>>> print("This is \x61 \ngood example")


This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contains curly braces {} as placeholders or replacement fields
which gets replaced.

We can use positional arguments or keyword arguments to specify the order.


P. Veera Prakash 27 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

The format() method can have optional format specifications. They are separated from field
name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the
given space. We can also format integers as binary, hexadecimal etc. and floats can be rounded or
displayed in the exponent format. There are a ton of formatting you can use. Visit here for all the
string formatting available with the format() method.

>>> # formatting integers


>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'

>>> # formatting floats


>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'

>>> # round off


>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

>>> # string alignment


>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'

Old style formatting

We can even format strings like the old sprintf() style used in C programming language. We use
the % operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

Common Python String Methods

P. Veera Prakash 28 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
There are numerous methods available with the string object. The format() method that we
mentioned above is one of them. Some of the commonly used methods are lower(), upper(),
join(), split(), find(), replace() etc. Here is a complete list of all the built-in methods to
work with strings in Python.

>>> "PrOgRaMiZ".lower()
'programiz'
>>> "PrOgRaMiZ".upper()
'PROGRAMIZ'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'

************************** III Unit – End *********************************

P. Veera Prakash 29 | P a g e

You might also like