0% found this document useful (0 votes)
12 views

u2_Python.docx

python

Uploaded by

balajidev29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

u2_Python.docx

python

Uploaded by

balajidev29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT II DATA TYPES IN PYTHON

Lists, Tuples, Sets, Strings, Dictionary, Modules: Module Loading and Execution – Packages – Making Your
OwnModule – The Python Standard Libraries.

In Python, the list is a collection of items of different data types. It is an ordered sequence of
items. A list object contains one or more items, not necessarily of the same type, which are
separated by comma and enclosed in square brackets [].

Syntax:
list = [value1, value2, value3,...valueN]

1. Create a List in Python


To create a list all you have to do is to place the items inside a square bracket [] separated by
comma. A list can have data items of same type or different types. This is the reason list comes
under compound data type.

# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]

# list of int, float and strings


mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]

# an empty list
nodata_list = []

2. Accessing the items of a list


Syntax to access the list items:
list_name[index]
where index should always be an integer value and indicates the item to be selected.

>>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]


>>> superstore[0]
'metro'

>>> superstore[9]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]

print(numbers[0])

print(numbers[5])

print(numbers[1])
Output
11
300
22

To access the list items from the end


Python allows you to use negative indexes. The idea behind this to allow you to access the list
elements starting from the end. For example an index of -1 would access the last element of the
list, -2 second last, -3 third last and so on.
# a list of strings Output:
my_list = ["hello", "world", "hi", "bye"] bye
print(my_list[-1]) world
print(my_list[-3])

To get a sublist in Python using slicing


A sublist from a list in Python using slicing operation. Lets say we have a list n_list having 10
elements, then we can slice this list using colon : operator.

Slicing of lists is allowed in Python wherein a part of the list can be extracted by specifying
index range along with the colon (:) operator which itself is a list.
The syntax for list slicing is,

List slicing returns


a part of the list from the start index value to stop index value which includes the start index
value but excludes the stop index value. Step specifies the increment value to slice by and it is
optional. For the list fruits, the positive and negative index breakdown is shown below.
# list of numbers
n_list = [1, 2, 3, 4, 5, 6, 7]

print(n_list[1:3])
Output:
# list items from beginning to 3rd
print(n_list[:3]) [2, 3.4]
# list items from 4th to end of list [1, 2, 3,4]
print(n_list[3:])
[4, 5, 6, 7]
# Whole list
print(n_list[:]) [1, 2, 3, 4, 5, 6, 7]

List Operations

There are various operations that we can perform on Lists.


Addition
There are several ways you can add elements to a list.
# list of numbers
n_list = [1, 2, 3, 4] Output
[1, 2, 3, 100, 4]
# 1. adding item at the desired location,value 100 at the fourth location [1, 2, 3, 100, 4, 99]
n_list.insert(3, 100) [1, 2, 3, 100, 4, 99, 11, 22]
print(n_list)

# 2. adding element at the end of the list


n_list.append(99)
print(n_list)

# 3. adding several elements at the end of list


n_list.extend([11, 22])
print(n_list)
Update elements
We can change the values of elements in a List. Lets take an example to understand this:
# list of numbers
n_list = [1, 2, 3, 4]

# Changing the value of 3rd item


n_list[2] = 100
Output:
print(n_list)
[1, 2, 100, 4]
# Changing the values of 2nd item to fourth items
n_list[1:4] = [11, 22, 33] [1, 11, 22, 33]
print(n_list)

Delete elements
# list of numbers
n_list = [1, 2, 3, 4, 5, 6] Output
del n_list[1] [1, 3, 4, 5, 6]
print(n_list)
[1, 2, 6]
del n_list[2:4]
print(n_list) []
# Deleting the whole list
del n_list

Deleting elements using remove(), pop() and clear() methods.


remove(item): Removes specified item from list.
pop(index): Removes the element from the given index.
pop(): Removes the last element.
clear(): Removes all the elements from the list.

# list of chars
ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']
# Deleting the element with value 'B' Output:
ch_list.remove('B')
print(ch_list) ['A', 'F', 'Z', 'O', 'L']

# Deleting 2nd element ['A', 'B','Z', 'O', 'L']


ch_list.pop(1)
print(ch_list) [ ]

# Deleting all the elements


ch_list.clear()
print(ch_list)
Assignment of List
When you assign an existing list variable to a new variable, an assignment (=) on lists does not
make a new copy. Instead, assignment makes both the variable names point to the same list in
memory. For example,
<class 'list'>

4. >>> type(forest)
<class 'list'>

5. >>> forest
['Lion', 'Tiger', 'Zebra']

6. >>> zoo[0] = "Fox"


7. >>> zoo
['Fox', 'Tiger', 'Zebra']

8. >>> forest
['Fox', 'Tiger', 'Zebra']

For example,
1. >>> lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
2. >>> len(lakes)
5
3. >>> numbers = [1, 2, 3, 4, 5]
4. >>> sum(numbers)
15
5. >>> max(numbers)
5
6. >>> min(numbers)
1

7. >>> lakes_sorted_new = sorted(lakes)


8. >>> lakes_sorted_new
['erie', 'huron', 'ontario', 'powell', 'superior']
Any & All function in Python
The any() function returns true if any of the element in the passed list is true, otherwise it returns
False. However, if the iterable object is empty, the any () function will return False.

Syntax
any(iterable)
The iterable object can be a list, tuple or dictionary.
Example 1
Using any() on Python Lists
# True since 1,3 and 4 (at least one) is true
l = [1, 3, 4, 0]
print(any(l))

# False since both are False Output


l = [0, False] True
print(any(l)) False
True
# True since 5 is true False
l = [0, False, 5]
print(any(l))

# False since iterable is empty


l = []
print(any(l))

Python all()
The all() method returns True when all elements in the given iterable are true. If not, it returns
False.

The syntax of all() method is:


all(iterable)
# all values true
l = [1, 3, 4, 5]
print(all(l)) Output

True
# all values false
False
l = [0, False]
False
print(all(l))
False
True
# one false value
l = [1, 3, 4, 0]
print(all(l))

# one true value


l = [0, False, 5]
print(all(l))

# empty iterable
l=[]
print(all(l))

4.15 Python Tuple


A tuple is similar to List except that the objects in tuple are immutable (unchangeable) which
means we cannot change the elements of a tuple once assigned. On the other hand, we can
change the elements of a list.

Tuple vs List
1. The elements of a list are mutable whereas the elements of a tuple are immutable.
2. When we do not want to change the data the tuple is a preferred data type whereas when we
need to change the data in future, list is a wise option.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
4. Elements of a tuple are enclosed in parenthesis( ) whereas the elements of list are enclosed in
square bracket [].

TO CREATE A TUPLE IN PYTHON


To create a tuple in Python, place all the elements in a ( ) parenthesis, separated by commas. A
tuple can have heterogeneous data items, a tuple can have string and list as data items as well.
Creating Tuples
# tuple of strings
my_data = ("hi", "hello", "bye")
print(my_data) Output: ('hi', 'hello', 'bye')

# tuple of int, float, string


my_data2 = (1, 2.8, "Hello World")
print(my_data2) Output: (1, 2.8, 'Hello World')

# tuple of string and list


my_data3 = ("Book", [1, 2, 3])
print(my_data3) Output: ('Book', [1, 2, 3])

Empty tuple:
my_data = ( )

Tuple with only single element:


When a tuple has only one element, we must put a comma after the element, otherwise Python
will not treat it as a tuple. If we do not put comma after 99 in the above example then python will
treat my_data as an int variable rather than a tuple.

#Example a tuple with single data item


my_data = (99,)

How to access tuple elements


We use indexes to access the elements of a tuple. Accessing tuple elements using positive
indexes.
We can also use negative indexes in tuple. Indexes starts with 0 that is why we use 0 to access
the first element of tuple, 1 to access second element and so on.

# tuple of strings
my_data = ("hi", "hello", "bye")

# displaying all elements


print(my_data) Output : ('hi', 'hello', 'bye')

# accessing first element


print(my_data[0]) Output : hi

# accessing third element


print(my_data[2]) Output : bye

1. TypeError: If you do not use integer indexes in the tuple. For example my_data[2.0] will raise
this error. The index must always be an integer.

2. IndexError: Index out of range. This error occurs when we mention the index which is not in
the range. For example, if a tuple has 5 elements and we try to access the 7th element then this
error would occur.

Negative indexes in tuples


Similar to list and strings we can use negative indexes to access the tuple elements from the end.

-1 to access last element, -2 to access second last and so on.


my_data = (1, 2, "Kevin", 8.9)

# accessing last element


print(my_data[-1])

print(my_data[-3])
Output
8.9
2

Accessing elements from nested tuples


Lets understand how the double indexes are used to access the elements of nested tuple. The first
index represents the element of main tuple and the second index represent the element of the
nested tuple.

my_data = (1, "Steve", (11, 22, 33))

# prints 'v'
print(my_data[1][3])

# prints 22
print(my_data[2][1])

Output:
v
22
Tuple Operations
Changing the elements of a tuple
We cannot change the elements of a tuple because elements of tuple are immutable. However we
can change the elements of nested items that are mutable. For example, in the following code, we
are changing the element of the list which is present inside the tuple. List items are mutable
that’s why it is allowed.
List

my_data = (1, [9, 8, 7], "World")


print(my_data) Output (1, [9, 8, 7], 'World')

# changing the element of the list


# this is valid because list is mutable
my_data[1][2] = 99
print(my_data) Output (1, [9, 8, 99], 'World')

# changing the element of tuple


# my_data[0] = 101 Error
# print(my_data)
# TypeError: 'tuple' object does not support item assignment

Delete operation on tuple


Tuple elements are immutable which also means that we cannot delete the elements of a tuple.
However deleting entire tuple is possible.
my_data = (1, 2, 3, 4, 5, 6)
print(my_data)

# not possible error


# del my_data[2]

# deleting entire tuple is possible


del my_data

Slicing operation in tuples


my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data) Output : (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data[2:5]) Output : 33, 44, 55

print(my_data[:4]) Output: index 0 to 3 elements from starting.


(11, 22, 33, 44)

From 5th element to last Output : (55, 66, 77, 88, 99)
print(my_data[4:])
Output:
Membership Test in Tuples (11, 22, 33, 44, 55, 66, 77, 88, 99)
True
in: Checks whether an element exists in the specified tuple.
False
not in: Checks whether an element does not exist in the specified
False
tuple.
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99) True
print(my_data)

# true
print(22 in my_data)

# false
print(2 in my_data)

# false
print(88 not in my_data)

# true
print(101 not in my_data)

Iterating a tuple Output


# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana") Apple

# iterating over tuple elements Orange


for fruit in my_tuple:
print(fruit) Grapes

Banana

4.16 Python - Dictionary


Like the list and the tuple, dictionary is also a collection type. However, it is not an ordered
sequence and it contains key-value pairs. One or more key:value pairs separated by commas are
put inside curly brackets to form a dictionary object.
Syntax:
dict = { key1:value1, key2:value2,... keyN:valueN }
The following declares a dictionary object.

>>> capitals={"USA" : "Washington", "France":"Paris", "India":"New Delhi"}

Dictionary Key value


Object
In the above example, capitals is a dictionary object. The left side of : is a key and right side of :
is a value. The key should be an immutable (unchangeable) object. A number, string or tuple can
be used as key.

The following definitions of dictionary are also valid:


>>> numNames={1:"One", 2: "Two", 3:"Three"}
>>> decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"}
>>> items={("Parker","Reynolds","Camlin"):"pen",("LG","Whirlpool","Samsung"):
"Refrigerator"}

However, a dictionary with a list as a key is not valid, as the list is mutable (changeable):
>>>dict={["Mango","Banana"]:"Fruit", ["Blue", "Red"]: "Colour"}
TypeError: unhashable type: 'list'
But, a list can be used as a value.
>>>dict={"Fruit":["Mango","Banana"], "Colour":["Blue", "Red"]}
The same key cannot appear more than once in a collection. If the key appears more than once,
only the last will be retained. The value can be of any data type. One value can be assigned to
more than one key.

>>>staff={"Krishna":"Officer", "Steve":"Manager", "John":"officer", "Anil":"Clerk",


"John":"Manager"}

>>>staff

Output
{"Krishna":"Officer", "Steve":"Manager", "Anil":"Clerk", "John":"Manager"}
However, when key 'John' is assigned two different values, only the latest is retained .
(overwriting the previous value).

Accessing a Dictionary

Dictionary is not an ordered collection, so a value cannot be accessed using an index in square
brackets. A value in a dictionary can be fetched using the associated key, using
the get() method. Specify the key in the get() method to retrieve its value.

>>>capitals={"USA":"New York", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}


>>>capitals.get("France")
Output : 'Paris'

>>>points={"p1":(10,10), "p2":(20,20)}
>>>points.get("p2")
Output: (20,20)
>>>numbers={1:"one", 2:"Two", 3:"three",4:"four"}
>>>numbers.get(2)

Output : 'Two’

Use the for loop to iterate a dictionary in the Python script.


capitals={"USA":"Washington", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}

for key in capitals:


print("Key = " + key + ", Value = " + capitals[key])

Output
Key = 'USA', Value = 'Washington'
Key = 'France', Value = 'Paris'
Key = 'Japan', Value = 'Tokyo'
Key = 'India', Value = 'New Delhi'

Updating a Dictionary
As mentioned earlier, the key cannot appear more than once. Use the same key and assign a new
value to it to update the dictionary object.
Example : 1
>>> captains={"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India']='Virat'
>>> captains['Australia']='Paine'
>>> captains
Output
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}

Example 2:
>>> capital={"Andhrapradesh":"Amaravathy", "Maharashtra ":"Mumbai",
"Tamilnadu":"Madras"}
>>> capital[‘Tamilnadu’]=’Chennai’

Output
>>> capital {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’}
>>>capital[‘Karnataka’]=’Bengalure’

Use a new key and assign a value to it. The dictionary will show an additional key-value pair in
it.
>>> capital {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’, ‘Tamilnadu’:’chennai’,
‘Karnataka’ : ‘Bengalure'}
Deleting Values from a Dictionary

Use the del keyword to delete a pair from a dictionary or the dictionary object itself. To delete a
pair, use its key as parameter. To delete a dictionary object, use its name.
>>> capital= {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
Del[capital]=’Karnataka’

Oultput
>>> capital {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’}
View Keys and Values

The keys() and values() methods of Python dictionary class return a view object consisting of
keys and values respectively, used in the dictionary.
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>>d1.keys()

dict_keys(['name', 'age', 'marks', 'course'])


The result of the keys() method is a view which can be stored as a list object. If a new key-
value pair is added, the view object is automatically updated.
>>> keys=d1.keys()

>>> keys
dict_keys(['name', 'age', 'marks', 'course'])
>>>d1.update({"college":"ABC college"})
>>> values
dict_values(['Steve', 21, 60, 'Computer Engg', ' ABC college'])
Multi-dimensional Dictionary

Let's assume there are three dictionary objects, as below:


>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}<

Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll
number as key and the above dictionaries at their value.
>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name':
'Asha', 'age': 20, 'marks': 70}}<

The students object is a two-dimensional dictionary. Here d1, d2 and d3 are assigned as values to
keys 1,2, and 3, respectively. students [1] returns d1.
>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}

The value of a key inside d1 can be obtained as below:


>>> students[1]['age']
25
Built-in Dictionary Methods

len - Returns the number of key:value pairs in the dictionary.


>>> lang={'A':('Ada','ActionScript'), 'P':("Python", "Perl","PHP")}
>>> len(lang)
Output : 2

max() - If all keys in the dictionary are numbers, the heighest number will be returned. If all
keys in the dictionary are strings, the one that comes last in alphabetical order will be returned.
Based on Ascii value.
>>> lang={'J':'Java', 'A': 'ActionScript', 'P':'Python'}
>>> max(lang)
Output 'P'

>>> num={5:"five", 100:"hundred",3:"three"}


>>> max(num)
Output 100

min() - If all keys in the dictionary are numbers, the lowest number will be returned. If all keys
in the dictionary are strings, the one that comes first in alphabetical order will be returned.
>>> lang={'J':'Java', 'A': 'ActionScript', 'P':'Python'}
>>> min(lang)
'A'
>>> num={5:"five", 100:"hundred",3:"three"}
>>> min(num)
Output 3

pop() - Returns the value associated with the key and the corresponding key-value pair is
removed.
>>> capital= {‘Andhrapradesh ‘: ’Amaravathy’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
>>>capital.pop(‘Maharashtra’)
‘Mumbai’
>>>capital
{‘Andhrapradesh ‘: ’Hyderabad’, ‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}

Clear - Returns empty object by deleting all the key-value pairs.


>>> capital.clear
>>>capital
Output
{}

Items - Returns a list of tuples, each tuple containing the key and value of each pair.
>>> capital= {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
>>> capital.items( )
dict_items(((‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’, ‘Tamilnadu’:’chennai’,
‘Karnataka’ : ‘Bengalure')])

Keys
Returns a list object comprising of the keys in the dictionary.
>>>capital.keys
dict_keys([‘Andhrapradesh’, ‘Maharashtra ‘, ‘Tamilnadu’, ‘Karnataka’ ])

values():
Returns a list object comprising of the values in the dictionary.
>>>capital.values
dict_values([‘Hyderabad’, ‘Mumbai’, ‘chennai’, ‘Bengalure'])

Sets
Sets are used to store multiple items in a single variable. Set is a built-in data types in Python
used to store collections of data. Example: birds = {"parrot", "peacok", "dove"}
A set is a collection which is both unordered and unindexed. Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

# Note: the set list is unordered, meaning: the items will appear in a random order.
List allows duplicates while Set doesn't allow duplicate elements, it omits to display.

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered
Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.

Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.
thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
o/p {'banana', 'cherry', 'apple'}

Get the Length of a Set


To determine how many items a set has, use the len() method.

Example
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
o/p 3
Set Items - Data Types

Set items can be of any data type:


set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:


A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
o/p
{True, 34, 40, 'male', 'abc'}

Type( )
myset = {"apple", "banana", "cherry"}
print(type(myset)
o/p <class 'set'>

The set() Constructor

It is also possible to use the set() constructor to make a set.


Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

o/p {'banana', 'apple', 'cherry'}

PYTHON STRINGS

String is a sequence of characters which are surrounded by either single quotation marks, or
double quotation marks or Triple quotation marks.
'hello' is the same as "hello". A Python string is an immutable sequence of characters; these
characters can be alphabets, numbers (from 0 to 9), white-spaces, etc.

Python does not have a character data type, a single character is simply a string with a length of
1. Square brackets can be used to access elements of the string.
To create a String in Python

1. We can use ‘ (single quotes), see the string str in the following code.
2. We can use ” (double quotes), see the string str2 in the source code below.
3. Triple double quotes “””” and triple single quotes ”’ are used for creating multi-line strings
in Python.
Output
# lets see the ways to create strings in Python
beginnersbook
str = 'beginnersbook'
Chaitanya
print(str)
Welcome to
Beginnersbook.com
str2 = "Chaitanya"
This is a tech
print(str2)
Blog

# multi-line string
str3 = """Welcome to
Beginnersbook.com"""
print(str3)

str4 = '''This is a tech


blog'''
print(str4)
2. How to access strings in Python

A string is nothing but an array of characters so we can use the indexes to access the characters
of a it. Just like arrays, the indexes start from 0 to the length-1.
You will get IndexError if you try to access the character which is not in the range. For
example,
if a string is of length 6 and you try to access the 8th char of it then you will get this error.
You will get TypeError if you do not use integers as indexes.
str = "Kevin"

# displaying whole string


print(str)
Output:
Kevin
# displaying first character of string
K
print(str[0])
v
n
i
# displaying third character of string
print(str[2])

# displaying the last character of the string


print(str[-1])

# displaying the second last char of string


print(str[-2])

Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])

Output
C:\Users\My Name>python demo_string1.py
e

Substring. Get the characters from position 2 to position 5 (not included):


b = "Hello, World!"
print(b[2:5])
Output
C:\Users\My Name>python demo_string2.py
llo,

STRIP
The strip() method removes any whitespace from the beginning or the end:
a=" Hello, World! "
print(a.strip( ))

Output
"Hello, World!"

Length()
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))
Output : 13

Lower
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

C:\Users\My Name> python demo_string_lower.py


O/P hello, world!

Upper
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

O/P HELLO, WORLD!

Replace Characters
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
O/P Jello, World!
SPLIT
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(","))
O/P ['Hello', 'World!']

Slicing
str = "Beginnersbook"
Slice a string to get a substring out of it.
# displaying whole string
print("The original string is: ", str)
O/P The original string is: Beginnersbook

# slicing 10th to the last character


print("str[9:] is: ", str[9:]) o/p str[9:] is: book
# slicing 3rd to 6th character
print("str[2:6]: ", str[2:6]) o/p str[2:6]: ginn

# slicing from start to the 9th character


print("str[:9]: ", str[:9]) o/p str[:9]: Beginners
Concatenation of strings in Python
The + operator is used for string concatenation in Python.
str1 = "One"
str2 = "Two"
str3 = "Three"
# Concatenation of three strings
print(str1 + str2 + str3)

O/p OneTwoThree
Repetition of string – Replication operator

use * operator to repeat a string by specified number of times.


str = "ABC"
# repeating the string str by 3 times
print(str*3)
Output
ABCABCABC
Membership Operators in Strings
in: This checks whether a string is present in another string or not. It returns true if the entire
string is found else it returns false.
not in: It works just opposite to what “in” operator does. It returns true if the string is not found
in the specified string else it returns false.
str = "Welcome to beginnersbook.com"
str2 = "Welcome"
str3 = "Chaitanya"
str4 = "XYZ"

print(str2 in str) Output True


print(str3 in str) Output False
print(str4 not in str) Output True

Relational Operators on Strings


The relational operators works on strings based on the ASCII values of characters.
The ASCII value of a is 97, b is 98 and so on.
The ASCII value of A is 65, B is 66 and so on.

str = "ABC"
str2 = "aBC"
str3 = "XYZ"
str4 = "XYz"

# ASCII value of str2 is > str


print(str2 > str)

# ASCII value of str3 is > str4


print(str3 > str4)
Output
True
False

String center()
The center() method returns a string which is padded with the specified character.
The syntax of center() method is: string.center(width[, fillchar])
center() Parameters
The center() method takes two arguments:
 width - length of the string with padded characters
 fillchar (optional) - padding character

The fillchar argument is optional. If it's not provided, space is taken as default argument.
center() Method With * fillchar
string = "Python is awesome"

new_string = string.center(24, '*')

print("Centered String: ", new_string)


Output
Centered String: ***Python is awesome****

String capitalize()

In Python, the capitalize() method converts first character of a string to uppercase letter and
lowercases all other characters, if any.
The syntax of capitalize() is: string.capitalize()
string = "python is AWesome."

capitalized_string = string.capitalize()

print('Capitalized String:', capitalized_string)

Output
Capitalized String: Python is awesome.

String count()
The string count() method returns the number of occurrences of a substring in the given
string.

string = "Python is Super, isn't it?"


substring = "is"
count = string.count(substring)
print("The count is:", count)

Output
The count is: 2

It also takes optional parameters start and end to specify the starting and ending positions in the
string respectively.
Python String find()
The find() method returns the index of first occurrence of the substring (if found). If not found, it
returns -1.
The syntax of find() method is: str.find(sub[, start[, end]] )

find() Parameters
The find() method takes maximum of three parameters:
 sub - It's the substring to be searched in the str string.
 start and end (optional) - substring is searched within str[start:end]

Return Value from find()


The find() method returns an integer value.
 If substring exists inside the string, it returns the index of first occurence of the substring.
 If substring doesn't exist inside the string, it returns -1.

Python String index()


The index() method returns the index of a substring inside the string (if found). If the substring is
not found, it raises an exception.
The syntax of index() method for string is:
str.index(sub[, start[, end]] )
index() Parameters

The index() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
The index() method is similar to find() method for strings.
The only difference is that find() method returns -1 if the substring is not found,
whereas index() throws an exception.

sentence = 'Python programming is fun.'


result = sentence.index('is fun')
print("Substring 'is fun':", result)

O/p : Substring 'is fun': 21

Python String isupper()


The string isupper() method returns whether or not all characters in a string are uppercased or
not.
The syntax of isupper() method is:

string.isupper()

The isupper() method returns:


 True if all characters in a string are uppercase characters
 False if any characters in a string are lowercase characters
# example string
string = "THIS IS GOOD!"
print(string.isupper());

Output: True

# lowercase string
string = "THIS IS not GOOD!"
print(string.isupper());
Output : False

Python String isdigit()


The isdigit() method returns True if all characters in a string are digits. If not, it returns False.
a=”20”
print(a.isdigit())

Command-line String Input

Python allows for command line input. That means we are able to ask the user for input.
The following example asks for the user's name, then, by using the input() method, the
program prints the name to the screen:
demo_string_input.py
print("Enter your name:")s
x = input()
print("Hello, " + x)

Save this file as demo_string_input.py, and load it through the command line:
C:\Users\Your Name>python demo_string_input.py

Escape Sequences
The escape character is used to invoke an alternative implementation of the subsequent character
in a sequence. In Python backslash \ is used as an escape character. Here is a list of escape
sequences and their purpose.
String Operators

Obviously, arithmetic operators don't operate on strings. However, there are special operators for
string processing.
String Formatting

Interpolation of objects of different types at placeholders inside a string is called string


formatting. The % operator (otherwise an arithmetic operator used to return the remainder of
division) is used to perform string formatting also. Format specification symbols (%d, %c, %f,
%s, etc) used in C language are utilized as placeholders in a string.
Packages
A package is actually a folder containing one or more module files.

Python - Creating and Installing a Package


create a package named mypackage, using the following steps:
 Create a new folder named D:\MyApp.
 Inside MyApp, create a subfolder with the name 'mypackage'.
 Create an empty __init__.py file in the mypackage folder.
 Using a Python-aware editor like IDLE, create modules greet.py and functions.py with
following code:
greet.py

def SayHello(name):
print("Hello " + name)
return

functions.py
def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

We have created our package called mypackage. The following is a folder structure:

Importing a Module from a Package

Now, to test our package, invoke the Python prompt from the MyApp folder.

D:\MyApp>python

Import the functions module from the mypackage package and call its power() function.
>>> from mypackage import functions
>>> functions.power(3,2)
9

It is also possible to import specific functions from a module in the package.

>>> from mypackage.functions import sum


>>> sum(10,20)
30
>>> average(10,12)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
NameError: name 'average' is not defined

__init__.py

The package folder contains a special file called __init__.py, which stores the package's content. It
serves two purposes:

1. The Python interpreter recognizes a folder as the package if it contains __init__.pyfile.


2. __init__.py exposes specified resources from its modules to be imported.

An empty __init__.py file makes all functions from above modules available when this package
is imported. Note that __init__.py is essential for the folder to be recognized by Python as a
package. You can optionally define functions from individual modules to be made available.

The __init__.py file is normally kept empty. However, it can also be used to choose specific
functions from modules in the package folder and make them available for import. Modify
__init__.py as below:

__init__.py
from .functions import average, power
from .greet import SayHello

The specified functions can now be imported in the interpreter session or another executable
script.

Create test.py in the MyApp folder to test mypackage.

test.py
from mypackage import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x)

Note that functions power() and SayHello() are imported from the package and not from their
respective modules, as done earlier. The output of above script is:

D:\MyApp>python test.py
Hello world
power(3,2) : 9
Install a Package Globally

Once a package is created, it can be installed for system wide use by running the setup script.
The script calls setup() function from setuptools module.
Let's install mypackage for system-wide use by running a setup script.
Save the following code as setup.py in the parent folder 'MyApp'. The script calls
the setup() function from the setuptools module. The setup() function takes various
arguments such as name, version, author, list of dependencies etc. The zip_safe argument defines
whether the package is installed in compressed mode or regular mode.

Example: setup.py
from setuptools import setup
setup(name='mypackage',
version='0.1',
description='Testing installation of Package',
url='#',
author='malhar',
author_email='mlathkar@gmail.com',
license='MIT',
packages=['mypackage'],
zip_safe=False)

Now execute the following command to install mypack using the pip utility. Ensure that the
command prompt is in the parent folder, in this case D:\MyApp.

D:\MyApp>pip install .
Processing d:\MyApp
Installing collected packages: mypack
Running setup.py install for mypack ... done
Successfully installed mypackage-0.1

Now mypackage is available for system-wide use and can be imported in any script or
interpreter.
D:\>python
>>> import mypackage
>>>mypackage.average(10,20)
15.0
>>>mypackage.power(10,2)
100

You may also want to publish the package for public use. PyPI (stands for Python Package
Index) is a repository of Python packages and is hosted at www.pypi.org

4.22 Module
A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:
Example
mymodule.py
def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
demo_module1.py:
import mymodule
mymodule.greeting("Jonathan")

O/p
C:\Users\My Name>python demo_module1.py
Hello, Jonathan
Variables in Module

The module can contain functions but also variables of all types (arrays, dictionaries, objects
etc):
mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Output
C:\Users\My Name>python demo_module2.py
36

Naming a Module

You can name the module file , but it must have the file extension .py
Re-naming a Module

You can create an alias when you import a module, by using the as keyword:
Create an alias for mymodule called mx:

import mymodule as mx
a = mx.person1["age"]
print(a)

Output
C:\Users\My Name>python demo_module3.py
36

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:

import platform

x = platform.system()
print(x)

O/p C:\Users\My Name>python demo_module4.py


Windows

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The
dir() function can be used on all modules, also the ones you create yourself.
The dir() function:
List all the defined names belonging to the platform module:
import platform

x = dir(platform)
print(x)

o/p

Import From Module

You can choose to import only parts from a module, by using the from keyword.
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Import only the person1 dictionary from the module:


from mymodule import person1

print (person1["age"])
o/p C:\Users\My Name>python demo_module6.py
36

Python - public, Private and Protected Access Modifiers


Private members of a class can be handled only from within the class.

Public members are accessible from outside the class.

Protected members of a class are accessible from within the class and are also available to its
sub-classes. No other environment is permitted access to it. This enables specific resources of the
parent class to be inherited by the child class.

All members in a Python class are public by default. Any member can be accessed from outside
the class environment.

Example: Public Attributes


class employee:
def __init__(self, name, sal):
self.name=name
self.salary=sal

You can access employee class's attributes and also modify their values, as shown below.
>>> e1=Employee("Kiran",10000)
>>> e1.salary
10000
>>> e1.salary=20000
>>> e1.salary
20000

Python's convention to make an instance variable protected is to add a prefix _ (single


underscore) to it. This effectively prevents it to be accessed, unless it is from within a sub-class.

Example: Protected Attributes

class employee:
def __init__(self, name, sal):
self._name=name # protected attribute
self._salary=sal # protected attribute

You can still perform the following operations:

>>> e1=employee("Swati", 10000)


>>> e1._salary
10000
>>> e1._salary=20000
>>> e1._salary
20000

Similarly, a double underscore __ prefixed to a variable makes it private.

Example: Private Attributes

class employee:
def __init__(self, name, sal):
self.__name=name # private attribute
self.__salary=sal # private attribute

>>> e1=employee("Bill",10000)
>>> e1.__salary
AttributeError: 'employee' object has no attribute '__salary'

Python performs name mangling of private variables. Every member with double underscore will
be changed to _object._class__variable. If so required, it can still be accessed from outside the
class, but the practice should be refrained.

>>> e1=Employee("Bill",10000)
>>> e1._Employee__salary
10000
>>> e1._Employee__salary=20000
>>> e1._Employee__salary
20000

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy