0% found this document useful (0 votes)
27 views51 pages

Unit-I PP

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)
27 views51 pages

Unit-I PP

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/ 51

Python Programming

Unit-I

INTRODUCTION

• Python is a general purpose High level programming


Language.
• Created by Guido Van Rossum in 1989 and made available to
the public only in 1991 .
• Python is very popular because of its simplicity, powerful
libraries, and concise code.
Applications of python

• Desktop applications
• Web applications
• Network applications
• Games development applications
• Data analysis applications
• Machine learning, Deep learning, Neural Network, Artificial
Intelligence and IoT
Features of Python

1. Easy to code:

Python is a high-level programming language. Python is very


easy to learn the language as compared to other languages like C,
C#, Javascript, Java, etc. It is very easy to code in python
language and anybody can learn python basics in a few hours or
days. It is also a developer-friendly language.
2. Free and Open Source:

Python language is freely available at the official website and you


can download it .
Since it is open-source, this means that source code is also
available to the public. So you can download it as, use it as well as
share it.

3. Object-Oriented Language:

One of the key features of python is Object-Oriented programming.


Python supports object-oriented language and concepts of
classes, objects encapsulation, etc.

4. GUI Programming Support:

Graphical User interfaces can be made using a module such as


PyQt5, PyQt4, wxPython, or Tk in python.PyQt5 is the most
popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in
python, we do not need to remember the system architecture, nor
do we need to manage the memory.

6. Extensible feature:

Python is a Extensible language. We can write us some


Python code into C or C++ language and also we can compile that
code in C/C++ language.

7. Python is Portable language:

Python language is also a portable language. For example, if


we have python code for windows and if we want to run this code
on other platforms such as Linux, Unix, and Mac then we do not
need to change it, we can run this code on any platform.

8. Python is Integrated language:

Python is also an Integrated language because we can easily


integrated python with other languages like c, c++, etc.

9. Interpreted Language:

Python is an Interpreted Language because Python code is


executed line by line at a time. like other languages C, C++, Java,
etc. there is no need to compile python code this makes it easier
to debug our code. The source code of python is converted into
an immediate form called bytecode.

10. Large Standard Library

Python has a large standard library which provides a rich set


of module and functions so you do not have to write your own
code for every single thing. There are many libraries present in
python for such as regular expressions, unit-testing, web
browsers, etc.

11. Dynamically Typed Language:

Python is a dynamically-typed language. That means the


type (for example- int, double, long, etc.) for a variable is decided
at run time not in advance because of this feature we don’t need
to specify the type of variable.

Comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing
code.

 Comments starts with a #, and Python will ignore them:


#This is a comment

print("Hello, World!")

Output:

Hello, World!

 Comments can be placed at the end of a line, and Python will


ignore the rest of the line:
print("Hello, World!") #This is a comment

Variables

 Variables are containers for storing data values.


 Unlike other programming languages, Python has no
command for declaring a variable.
 A variable is created the moment you first assign a value to
it.

Variables do not need to be declared with any particular type and


can even change type after they have been set.

x=5

y = "John"

print(x)

print(y)

Output:
5

John

Variable Names

A variable can have a short name (like x and y) or a more


descriptive name (age, carname, total_volume). Rules for Python
variables:

 A variable name must start with a letter or the underscore


character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are
three different variables)

Data Types

 In programming, data type is an important concept.


 Variables can store data of different types, and different
types can do different things.
 Python has the following data types built-in by default, in
these categories:
Operators

Operators are special symbols in Python that carry out arithmetic


or logical computation. The value that the operator operates on is
called the operand.

Example:

>>>2+3
5

Arithmetic operators

Arithmetic operators are used to perform mathematical


operations like addition, subtraction, multiplication, etc.
x = 15
y=4

# Output: x + y = 19
print('x + y =',x+y)

# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)

Output:

x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

Numbers:

There are three numeric types in Python:

 int
 float
 complex
Variables of numeric types are created when you assign a value
to them:

>>>x = 1 # int
>>>y = 2.8 # float
>>>z = 1j # complex

To verify the type of any object in Python, use the type() function:

>>>print(type(x))
>>>print(type(y))
>>>print(type(z))
Output:

<class 'int'>

<class 'float'>

<class 'complex'>

int

int, or integer, is a whole number, positive or negative,


without decimals, of unlimited length.

x=1
y = 35656222554887711
z = -3255522

float

float, or "floating point number" is a number, positive or


negative, containing one or more decimals.

x = 1.10
y = 1.0
z = -35.59

float can also be scientific numbers with an "e" to indicate the


power of 10.

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))
output

<class 'float'>

<class 'float'>

<class 'float'>

Complex

Complex numbers are written with a "j" as the imaginary part:

x = 3+5j
y = 5j
z = -5j

Type Conversion

You can convert from one type to another with the int(), float(),
and complex() methods:

x=1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)

#convert from int to complex:


c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Output:

1.0
2
(1+0j)
<class 'float'><class 'int'><class 'complex'>

Type casting:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Booleans

In programming you often need to know if an expression is True


or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

print(10 > 9)
print(10 == 9)
print(10 < 9)

Output:
True

False

False

Sequences
Sequences allow you to store multiple values in an organized and
efficient fashion. There
are several sequence types: lists ,tuples and strings.

List

Properties of List

1.List are ordered collection of objects.

 The order in which you specify the elements when you define
a list is an innate characteristic of that list and is maintained
for that list’s lifetime.
>>> L=[1,2,3,4,5]

>>>L[0]=10

[10,2,3,4,5]
>>>L[1]

2.List can contain Arbitrary objects.

 The elements of a list can all be the same type or the


elements can be of varying types
 Lists can even contain complex objects, like functions,
classes, and modules,
>>>L=[“hello”,3,4.5]

3.List can accessed using its index.

Individual elements in a list can be accessed using an index


in square brackets. List indexing starts with zero.

>>>L[2]

4.List are Mutable.

Once a list is created, the elements can be modified .

>>>L[2]=10

5.List are dynamic.

-add elements

-remove elements

6.List can be nested.

You have seen that an element in a list can be any sort of


object. That includes another list. A list can contain sublists,
which in turn can contain sublists themselves, and so on to
arbitrary depth.

M=[[1,2],[2,3],[4,5],[6,7]]

>>>M[0][0]

>>>M[2][0]

>>>M[3][0]

Creating a list:

Creating a list is as simple as putting different comma-separated


values between square brackets. For example

>>>L =[] //empty list

>>> L=[1,2,3]

Also use constructor to create a list.

>>>L=list([2,3,4])

Accessing the items

You access the list items by referring to the index number.

>>>L[0]

Negative Indexing can also be used.Negative indexing begins


from the end, -1 refers to the last item, -2 refers to the second last
item etc.
>>>L[-1]

Accessing range of items

You can specify a range of indexes by specifying where to


start and where to end the range.When specifying a range, the
return value will be a new list with the specified items.

Syntax:

L[start:end:step count Step count is an optional one.

A=[1, 2, 3, 4, 5, 6, 7, 8]
0 1 2 34 5 6 7

>>>A[ : ] //prints all the elements

>>>A[:3]//prints the element at the index 0 to 2 not including 3 i.e


[1,2,3]

>>>A[ : :2] // prints [1,3,5,7] 1,4,7

>>>A[ :-3]// prints[1,2,3,4,5]

>>>A[ : :-1]//prints[8,7,6,5,4,3,2,1]

>>>A[ : :-2] 8,6 4, 2

change item value

Since list is mutable you can change the value of a List.

>>>A[0]=10

>>>A

[10,2,3,4,5,6,7,8]
Check item exist or not

To determine if a specified item is present in a list use


the in keyword: not in is just opposite to in operator.

>>>if 12 in A:

print(“yes element is present”)

else:

print(“no element is not present”)

yes element is present

>>>if 23 not in A:

print(“not present”)

not present

Finding length of a List

To determine how many items a list has, use


the len() function:

>>>print(len(A))

Add items

To add an item to the end of the list, use


the append() method:

>>>A

[10,2,3,4,5,6,7,8]
>>>A. append(20)

>>>A

[10,2,3,4,5,6,7,8,20]

To add an item at the specified index, use


the insert() method.

insert( pos, element)

>>>A.insert(1,25)

[10,25,2,3,4,5,6,7,8,20]

Join Two Lists

There are several ways to join, or concatenate, two or more


lists in Python.One of the easiest ways are by using the + operator.

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

[a,b,c,1,2,3]

For Loop

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

for x in list2:
list1.append(x)
print(list1)
[a,b,c,1,2,3]

extend()

The extend() method adds the specified list elements (or any
iterable) to the end of the current list.

c=[1,3,5,7,8,10]

>>>c.extend([11,22,33,44,55])

>>>c

[1,3,5,7,8,10,11,22,33,44,55]

Remove items

There are several methods to remove items from a list:

remove()

The remove() method removes the specified item:

>>>A

[10,25,2,3,4,5,6,7,8,20]

>>>A.remove(10)

>>>A

[25,2,3,4,5,6,7,8,20]

pop()

The pop() method removes the specified index, (or the last
item if index is not specified):

>>>A.pop()
[25,2,3,4,5,6,7,8]

>>>A.pop(1)

[25,3,4,5,6,7,8]

del keyword

The del keyword removes the specified index

>>>del [1]

[25,4,5,6,7,8]

The del keyword can also delete the list completely.

>>>del A

>>>A

[]

Clear()

The clear() method removes all the elements int a list.

>>>A.clear()

[]

Other List Methods:

count()

Returns the number of elements with the specified value.


Syntax

list.count(value)

>>>fruits = ['apple', 'banana', 'cherry']


>>>x = fruits.count("cherry")

>>>x

index()

The index() method returns the position at the first


occurrence of the specified value.

>>>s = [4, 55, 64, 32, 16, 32,32]


>>>x = s.index(32)

reverse()

The reverse() method reverses the sorting order of the


elements.

syntax:

list.reverse()

>>>A=[1,5,7,3,8,10]

>>>A.reverse()
>>>A

[10,8,3,7,5,1]

sort()
The sort() method sorts the list ascending by default.

syntax:

list.sort()

>>>A

[10,8,3,7,5,1]

>>>A.sort()

>>>A

[1,3,5,7,8,10]

copy()

The copy() method returns a copy of the specified list.

>>>c=A.copy()

>>>c

[1,3,5,7,8,10]

max

-returns an item from the list which is having maximum value

>>>L=[3,6,9,17,12,45]

>>>max(L)

>>>45

min

-returns an item from the list which is having min value

>>>L=[3,6,9,17,12,45]
>>>min(L)

Operator:

>>>[1,2,3]+[4,5,6]

>>>[1,2,3,4,5,6]

Repetition operator

>>>L=[1,2,3]

>>> L*3 ///repeats the elements given number of times

[1, 2, 3, 1, 2, 3, 1, 2, 3]

For loop

L=[1,2,3]

for x in L:

print(x)

123

Tuple

 A tuple is a collection which is ordered and unchangeable. In


Python tuples are written with round brackets.

 Tuples are sequences, just like lists.

 Tuples are identical to lists in all respects, except for the


following properties:

 Tuples are defined by enclosing the elements in


parentheses (()) instead of square brackets ([]).
 Tuples are immutable.

 Why use a tuple instead of a list?

 Sometimes you don’t want data to be modified. If the


values in the collection are meant to remain constant for
the life of the program, using a tuple instead of a list
guards against accidental modification.
 If we want the value of the dictionary as an immutable
type, A tuple can be used for this purpose, whereas a list
can’t be.
 Program execution is faster when manipulating a tuple
than it is for the equivalent list. (This is probably not going
to be noticeable when the list or tuple is small.)

Creating a Tuple

 Creating a list is as simple as putting different comma-


separated values between parentheses. For example
c =(1,2,3,4,5)
 Also use constructor to create a tuple.
t=tuple((1,2,3,4,5))
Create Tuple With One Item
To create a tuple with only one item, you have to add a
comma after the item, otherwise Python will not recognize it
as a tuple.
>>> a=(1)
>>> type(a)
<class 'int'>
>>> a=(1,)
>>> type(a)
<class 'tuple'>
Accessing the items
You can access tuple items by referring to the
index number, inside square brackets

>>>print(t[2])

Negative indexing also used which begins from the


end, -1 refers to the last item, -2 refers to the second last
item etc.

>>>print(t[-1])

You can specify a range of indexes by specifying where


to start and where to end the range.When specifying a range,
the return value will be a new tuple with the specified items.

>>>f=("apple", "banana", "cherry", "orange", "kiwi", "melon


", "mango")
>>> print(f[2:5])

output:
('cherry', 'orange', 'kiwi')

Specify negative indexes if you want to start the search


from the end of the tuple:

>>>f =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
>>>print(f[-4:-1])

Output:

('orange', 'kiwi', 'melon')

Change Tuple Values

Once a tuple is created, you cannot change its values.


Tuples are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple


into a list, change the list, and convert the list back into a
tuple.

>>> x=tuple((2,3,4,5))

>>> x

(2, 3, 4, 5)

>>> print(x[3])

>>>x[3]=55

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment


Loop Through a Tuple

You can loop through the tuple items by using a for


loop.

t = ("apple", "banana", "cherry")


for x in t:
print(x)

Output:
apple
banana
cherry
Check if Item Exists
To determine if a specified item is present in a tuple
use the in keyword:
t= ("apple", "banana", "cherry")
if "apple" in t:
print("Yes, 'apple' is in the fruits tuple")
Output:
Yes, 'apple' is in the fruits tuple
Tuple Length
To determine how many items a tuple has, use the
len() method:
>>> print(len(t))

Output:3

Add Items

Once a tuple is created, you cannot add items to it. Tuples


are unchangeable.

>>> t=(1,2,3)
>>>len(t)
3
>>>t[4]=10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment.
Remove Items
Tuples are unchangeable, so you cannot remove items
from it, but you can delete the tuple completely:
>>> a = (1,2,3)
>>> del a
>>> print(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Join Two Tuples

To join two or more tuples you can use the + operator:


t1 = ("a", "b" , "c")
t2 = (1, 2, 3)
t3 = t1 + t2
print(t3)
Output:('a', 'b', 'c', 1, 2, 3)

Tuple Methods
count()
Returns the number of times a specified value occurs in
a tuple

t = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = t.count(5)
print(x)
Outut:2

index()
Searches the tuple for a specified value and returns the
position of where it was found.

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)

Output:3

Dictionary

A dictionary is a collection which is ordered, changeable and


unindexed. In Python dictionaries are written with curly brackets,
and they have keys and values.

Dictionaries and lists share the following characteristics:

 Both are mutable.


 Both are dynamic. They can grow and shrink as needed.
 Both can be nested. A list can contain another list. A
dictionary can contain another dictionary. A dictionary can
also contain a list, and vice versa.

Dictionaries differ from lists primarily in how elements are


accessed:

 List elements are accessed by their position in the list, via


indexing.(slicing and indexing not possible in dictionary).
 Dictionary elements are accessed via keys.

Defining a Dictionary
A dictionary consists of a collection of key-value pairs. Each
key-value pair maps the key to its associated value.

You can define a dictionary by enclosing a comma-separated


list of key-value pairs in curly braces ({}). A colon (:) separates
each key from its associated value.

d={
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
Example:

dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(dict1)

Output:{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

It is also possible to use the dict() constructor to make


a new dictionary:

dict3 = dict(brand="Ford", model="Mustang", year=1964)


print(dict3)

Accessing Items

You can access the items of a dictionary by referring to its


key name, inside square brackets:

>>>dict1["model"]

Mustang

>>> dict1[“brand "]

Ford

There is also a method called get() that will give you the
same result:

dict1.get("model")

Mustang

Change Values

You can change the value of a specific item by referring to


its key name:

dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1["year"] = 2018

Loop Through a Dictionary

 When looping through a dictionary, the return value are


the keys of the dictionary, but there are methods to return
the values as well.
for x in dict1:
print(x)

Output:
brand
model
year
 Print all values in the dictionary, one by one:
for x in dict1:
print(dict1[x])

Output:
Ford
Mustang
1964
 You can also use the values() method to return values of a
dictionary:
for x in dict1.values():
print(x)

Output:
Ford
Mustang
1964
 Loop through both keys and values, by using the items()
method:

for x, y in dict1.items():
print(x, y)
Output:
brand Ford
model Mustang
year 1964
Check if Key Exists
To determine if a specified key is present in a dictionary use
the in keyword:
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in dict1:
print("Yes, 'model' is one of the keys in the dict1
dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary has,
use the len() function.
print(len(dict1))

Adding Items

Adding an item to the dictionary is done by using a new


index key and assigning a value to it:

dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1["color"] = "red"
print(dict1)

Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
There are several methods to remove items from a
dictionary:
 The pop() method removes the item with the specified key
name:

dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1.pop("model")
print(dict1)
Output:
{'brand': 'Ford', 'year': 1964}
 The popitem() method removes the last inserted item
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1.popitem()
print(dict1)
Output:

{'brand': 'Ford', 'model': 'Mustang'}


 The del keyword removes the item with the specified key
name:
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del dict1["model"]
print(dict1)
Output:
{'brand': 'Ford', 'year': 1964}
 The del keyword can also delete the dictionary completely:
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del dict1
print(dict1) #this will cause an error because "dict1" no
longer exists.
Output:
Error

 The clear() method empties the dictionary:


dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1.clear()
print(dict1)
Output:
{}
Copy a Dictionary

 You cannot copy a dictionary simply by typing dict2 = dict1,


because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.

Make a copy of a dictionary with the copy() method:

dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict2= dict1.copy()
print(dict2)
Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


Nested Dictionary
 In Python, a nested dictionary is a dictionary inside a
dictionary. It's a collection of dictionaries into one single
dictionary.
people = {1: {'name': 'Akila', 'age': '21', 'Dept': 'MECH'},
2: {'name': 'Anand', 'age': '21', 'Dept': 'MECH'}
}

print(people)
Output:
{1: {'name': 'Akila', 'age': '21', 'Dept': 'MECH'}, 2: {'name': 'Anand',
'age': '21', ‘Dept’: 'MECH'}}
Access elements of a Nested Dictionary
 To access element of a nested dictionary, we use indexing
[] syntax in Python.
print(people[1]['name'])
print(people[1]['age']))
print(people[1]['Dept'])
Output:
Akila
21
MECH
Add element to a Nested Dictionary
people[3] = {}
people[3]['name'] = 'Priya'
people[3]['age'] = '21'
people[3]['Dept'] = 'MECH'
people[3]['Address'] = 'Salem'
print(people[3])
Output:
{'name': 'Priya', 'age': '21', 'Dept': 'MECH', 'Address':
'Salem'}
Add another dictionary to the nested dictionary
people[4] = {'name': 'Karthik', 'age': '21', 'Dept': 'Mech'}
print(people[4])
Output:
{'name': 'Karthik', 'age': '21', 'Dept': 'Mech'}

Delete elements from a Nested Dictionary


del people[3], people[4]
print(people)
Output:
{1: {'name': 'Akila', 'age': '21', 'Dept': 'MECH'}, 2: {'name': 'Anand',
'age': '21', 'dept': 'MECH'}}

Update() Method
 The update() method inserts the specified items to the
dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car. update({"color": "White"})


print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}
Strings

 String literals in python are surrounded by either single


quotation marks, or double quotation marks.

e.g., 'hello' is the same as "hello". ‘k’

 triple quotation is used to declare multi line strings.

 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.

Creating a string

s = 'Hello'
t = "Hello"

m = """This is a long string that is

spread across two lines."""

Input

>>>name = input('Enter a string: ')

Empty string

>>>sep='‘

Length

>>>len('Hello')

Concatenation and repetition

Expression Result

‘AB’+’CD’ ‘ABCD’

‘a’+’7’+’b’ ‘a7b’

Hi*3 ‘HiHiHi’

The Membership operator

The in operator is used to tell if a string contains something.

s=”hello welcome”

>>>if 'e' in s:

print('Your string contains the letter e.')

Output:'Your string contains the letter e.'


>>>print (‘a’ in s)

false

>>>if ';' not in s:

print('Your string does not contain any semicolons.')

Output:'Your string does not contain any semicolons.

Indexing

>>>s=“Python”

>>>s[0] P first character of s

>>>s[1] y second character of s

>>>s[-1] n last character of s

>>>s[-2] o second-to-last character of s

Slices

• A slice is used to pick out part of a string. It behaves like a


combination of indexing and the range function.
>>>s='abcdefghij'.

• index: 0 1 2 3 4 5 6 7 8 9
• letters: a b c d e f g h i j
statement Output Comment

>>>s[2:5] cde characters at indices 2, 3, 4

>>>s[ :5] abcde first five characters

>>>s[5: ] fghij characters from index 5 to the end


>>>s[-2: ] ij last two characters

>>>s[ : ] abcdefghij entire string

>>>s[1:7:2] bdf characters from index 1 to 6, by


twos

>>>s[ : :-1] jihgfedcba a negative step reverses


the string

Changing individual characters of a string

Strings are immutable in Python

>>>s[4]='X‘ //trying to change the character at the index 4

Output: error

Looping

s=”hello”

for c in s:

print(c)

Output:

l
o

String methods

startswith()

The startswith() method returns True if the string starts with the
specified value, otherwise False.

t = "Hello, welcome to my world."


x = t.startswith("Hello")
print(x)
Output: True

capitalize()

The capitalize() method returns a string where the first


character is upper case.

s = "hello, and welcome to python world."


x = s.capitalize()
print (x)

output:Hello, and welcome to python world.

endswith()

The endswith() method returns True if the string ends with


the specified value, otherwise False.

t= "Hello, welcome to python world."


x = t.endswith(".")
print(x)

Output: True
find()

 The find() method finds the first occurrence of the specified


value.
 The find() method returns -1 if the value is not found.
 The find() method is almost the same as the index() method,
the only difference is that the index() method raises an
exception if the value is not found. (See example below)
txt = "Hello, welcome to python world."
x = txt.find("welcome")
print(x)

Output:7

upper()

The upper() method returns a string where all characters are


in upper case.

txt = "Hello my friends"


x = txt.upper()
print(x)
Output:HELLO MY FRIENDS
swapcase()

The swapcase() method returns a string where all the upper


case letters are lower case and vice versa.

txt = "HELLO MY FRIENDS"


x = txt.swapcase()
print(x)
Output:hello my friends

isalpha()

The isalpha() method returns True if all the characters are


alphabet letters (a-z).

Example of characters that are not alphabet letters: (space)!#%&?


etc.

txt = "Company10"
x = txt.isalpha()
print(x)
Output:false
isdigit()

The isdigit() method returns True if all the characters are


digits, otherwise False.

a = "123”
b = "x456”
print(a.isdigit())
print(b.isdigit())
Output:True
false
split()

 The split() method splits a string into a list.


 You can specify the separator, default separator is any
whitespace.
txt = "welcome to the python"
x = txt.split()
print(x)
Output: [‘welcome’, ‘to’ ,‘the’, ‘python’]

join()

The join() method takes all items in an iterable and joins


them into one string.

A string must be specified as the separator.

>>> l=['hello','welcome','to','python']

>>> l

['hello', 'welcome', 'to', 'python']

>>> s='#'.join(l)

>>> s

'hello#welcome#to#python'

Escape sequence

Escape characters are characters that are generally used to


perform certain tasks and their usage in code directs the compiler
to take a suitable action mapped to that character.

Single Quote (\')

txt = 'It\'s alright.'

print(txt)

Output:

It's alright.

Backslash (\\)

txt = "This will insert one \\ backslash."


print(txt)

Output:

This will insert one \ backslash.

New line(\n)

txt = "Hello\nWorld!"

print(txt)

Output:

Hello

World!

Tab(\t)

txt = "Hello\tWorld!"

print(txt)

Output:

Hello World!

Bell sound(\a)

txt = "Hello\aWorld!"

print(txt)

Output:

HelloWorld! //after printing hello you may hear bell sound


and then world is printed

String Format
we cannot combine strings and numbers like this:

age = 36

txt = "My name is Aravind, I am " + age

print(txt)

Output:

Error

But we can combine strings and numbers by using


the format() method!

The format() method takes the passed arguments, formats them,


and places them in the string where the placeholders {} are:

Ex:

age = 36
txt = "My name is Aravind, and I am {}"
print(txt.format(age))

Output:

My name is John, and I am 36

Ex:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

Output:
I want 3 pieces of item 567 for 49.95 dolla

Set

A set is a collection which is unordered and unindexed. In


Python sets are written with curly brackets.

Creating a list:

 Creating a set is as simple as putting different comma-


separated values between set brackets
>>>s = {"apple", "banana", "cherry"}
>>>print(s)

output:
{"banana", "apple", "cherry"}

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


set.
s=set({"apple", "banana", "cherry"})
print(s)
 Sets are unordered, so you cannot be sure in which
order the items will appear.
Access Items
You cannot access items in a set by referring to an index,
since sets are unordered the items has no index.

But you can loop through the set items using a for loop, or
ask if a specified value is present in a set, by using the in keyword.
s = {"apple", "banana", "cherry"}
for x in s:
print(x)
Output:
banana
cherry
apple
Checking the Existence of an Item

s = {"apple", "banana", "cherry"}


print("banana is" in set)
Change Items
Once a set is created, you cannot change its items, but you
can add new items.

Add Items
 To add one item to a set use the add() method.
 To add more than one item to a set use the update()
method.
s = {"apple", "banana", "cherry"}
s.add("orange")
print(s)
Output:
{'banana', 'orange', 'apple', 'cherry'}
 Add multiple items to a set, using the update() method:

s = {"apple", "banana", "cherry"}


s.update(["orange", "mango", "grapes"])
print(s)
Print the Length of a Set

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


method.

s= {"apple", "banana", "cherry"}


print(len(s))
Remove Item

To remove an item in a set, use the remove(), or the discard()


method or pop() method.
remove()
If the item to remove does not exist, remove() will raise
an error.
s = {"apple", "banana", "cherry"}
s.remove("banana")
print(s)
discard()
If the item to remove does not exist, discard() will NOT
raise an error.
s = {"apple", "banana", "cherry"}
s.discard("banana")
print(s)
pop()
Removes the last item
clear()
The clear() method empties the set.
s.clear()
del keyword
The del keyword will delete the set completely:
del s
Join Two Sets
 The union() method returns a new set with all items
from both sets.
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Output:
{'b', 2, 1, 'c', 'a', 3}
 The update() method inserts the items in set2 into set1.
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Output:
{'b', 2, 1, 'c', 'a', 3}
 Both union() and update() will exclude any duplicate
items.
Set Methods:

difference()
Return a set that contains the items that only exist in set x,
and not in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
Output:
{'cherry', 'banana'}

intersection()

Return a set that contains the items that exist in both set x,
and set y.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
Output:
{'apple'}

issubset()
Return True if all items set x are present in set y:

x = {"a", "b", "c"}


y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
Output:
True

isdisjoin()
Return True if no items in set x is present in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
Output:
True
union()-Return a set that contains all items from both sets,
duplicates are excluded:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z)
Output:

{'apple', 'cherry', 'banana', 'microsoft', 'google'}

Other Methods:
add() - Adds an element to the set
clear() - Removes all the elements from the set
copy() - Returns a copy of the set

You might also like