strings and dictionary in python
strings and dictionary in python
Functions in python:
A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. A function can return data as a
result.
1
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
def add():
n1=10
n2=20
sum=n1+n2
print(sum) #o/p 30
def add(n1,n2):
sum=n1+n2
print(sum) #o/p 30
def add(n1,n2):
sum=n1+n2
return(sum)
String
2
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Example:
str1='This is a string in Python'
print(str1)
Multi-line Strings
String as Array
greet='hello'
print(greet[0])
print(greet[1])
print(greet[2])
print(greet[3])
print(greet[4])
print(greet[5]) #IndexError: string index out of range
Negative Index
greet='hello'
print(greet[-5])
3
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
print(greet[-4])
print(greet[-3])
print(greet[-2])
print(greet[-1])
print(greet[0])
greet='hello'
greet[0]='A' #TypeError:'str' object does not support item
assignment
String Operators
Operato
r Description Example
+ Appends the second string to the first a='hello'
b='world'
a+b
#output: 'helloworld'
* Concatenates multiple copies of the same string a='hello'
a*3
#output: 'hellohellohello'
[] Returns the character at the given index a = 'Python'
a[2]
#output: t
[:] Fetches the characters in the range specified by two a = 'Python'
index operands separated by the : symbol a[0:2]
#output: 'Py'
in Returns true if a character exists in the given string a = 'Python'
4
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Operato
r Description Example
'x' in a #output: False
'y' in a #output: True
'p' in a #output: False
not in Returns true if a character does not exist in the given a = 'Python'
string 'x' not in a #output: True
'y' not in a #output: False
endswith() Returns true if the string ends with the specified value
Example:
s="good morning"
print(s.endswith("ing"))
output: True
s="googd morning"
print(s.endswith("ig"))
5
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
output: False
find() Searches the string for a specified value and returns the position
of where it was found
Example:
s="Hi good morning"
print(s.find("good"))
output:3
s="Hi good morning good"
print(s.find("god"))
output:-1
index() Searches the string for a specified value and returns the position
of where it was found
Example:
s="Hi good morning good"
print(s.index("good"))
output:3
s="Hi good morning good"
print(s.index("god"))
output:error
isalpha() Returns True if all characters in the string are in the alphabet
Example:
s="company"
print(s.isalpha())
output: True
6
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
s="123abcd"
print(s.isdigit())
output:False
s="123"
print(s.isdigit())
output: True
islower() Returns True if all characters in the string are lower case
Example:
s="good morning"
print(s.islower())
output: True
isupper() Returns True if all characters in the string are upper case
Example:
s="GOOD MORNING"
print(s.isupper())
output: True
7
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
rfind() Searches the string for a specified value and returns the last
position of where it was found
Example:
s="Hi, good morning Have a good Day"
print(s.rfind("good"))
output: 24
rindex() Searches the string for a specified value and returns the last
position of where it was found
s="Hi, good morning Have a good Day"
print(s.rindex("good"))
output: 24
8
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
split() Splits the string at the specified separator, and returns a list
Example:
s = "welcome to the python class"
print(s.split())
output: ['welcome', 'to', 'the', 'python', 'class']
startswith() Returns true if the string starts with the specified value
Example:
txt = "Hello, welcome to my world."
print(txt.startswith("Hello"))
output: True
swapcase() Swaps cases, lower case becomes upper case and vice versa
Example:
s = "Hello, Welcome to my WORLD."
print(s.swapcase())
output: hELLO, wELCOME TO MY world.
Dictionary
Dictionaries are used to store data values in key:value pairs.
9
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example:
Output
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
Output
Empty Dictionary:
{}
10
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Output:
11
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Output
Empty Dictionary:
{}
12
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output
Methods of dictionary:
Method Description
print(numbers)
Output: {}
copied_marks = original_marks.copy()
13
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
print(original_marks)
print(copied_marks)
Output: {'Physics': 67, 'Maths': 87}
{'Physics': 67, 'Maths': 87}
Example:
# keys for the dictionary
alphabets = {'a', 'b', 'c'}
print(dictionary)
items() Returns a list containing a tuple for each key value pair
Example:
marks = {'Physics':67, 'Maths':87}
print(marks.items())
Output: dict_items([('Physics', 67), ('Maths', 87)])
14
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
Example:
person = {'name': 'Phill'}
File in python:
File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk). When we want to read from or write to a file we need to open it
first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
1. Open a file
15
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Syntax: file_object=open(file_name,mode)
Filename
mode.
"r" - Read - Default value. Opens a file for reading, error if the file does notexist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
demofile.txt
Good morning
Hello
Read from a File:
Welcome to python class
Example 1:
PESITM Shivamogga
f = open("demofile.txt", "r")
print(f.read())
f.close()
output:
Good morning
16
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Hello
Welcome to python class
PESITM Shivamogga
f = open("demofile.txt", "r")
print(f.read(4))
f.close()
output:
Good
f = open("demofile.txt", "r")
print(f.readline()) #Read one line of the file:
f.close()
output:
Good morning
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
output:
17
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Good morning
Hello
Welcome to python class
To write to an existing file, you must add a parameter to the open() function:
Example 1: Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
output:
Good morning
Hello
Welcome to python class
Now the file has more content!
18
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
output:
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example 2: Create a new file if it does not exist:
f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")
19