Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Unit4 Part1

Strings in Python can be defined using single or double quotes and allow multiline strings defined using triple quotes; characters within a string can be accessed using indexes starting from 0; Python strings support various built-in methods like lower(), upper(), split(), join(), replace(), and format operators like %s for formatting strings.

Uploaded by

Saif Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Unit4 Part1

Strings in Python can be defined using single or double quotes and allow multiline strings defined using triple quotes; characters within a string can be accessed using indexes starting from 0; Python strings support various built-in methods like lower(), upper(), split(), join(), replace(), and format operators like %s for formatting strings.

Uploaded by

Saif Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python Strings

String is a sequence of characters enclosed in ‘ ‘or “”


Creating strings:
1. Create instance of str class.
s=str()
s=“abc”

2. Assign string to a variable


s=“abc”

3. Multiline strings: enclose in triple quotes


msg=‘’’ hi
how r u?
fine? ‘’’
Refer string characters:
Characters are referred by index. Index begins with zero.
msg=“welcome”
msg[0]=‘w’, msg[1]=‘e’, msg[2]=l , ……….
Python Strings: Formatting
• Use string format operator %. % with format symbol followed by % with value to be printed
• Value can be static text or variable

Print static data


Ex1: print("My name is %s “ % ‘xyz') // print static string
output: My name is xyz

Ex2: print "My age is %d “ % 20) // print number


output: My age is 20

Ex3: print "My name is %s age is %d“ % (‘xyz‘,20)) // print multiple values
Output: My name is xyz age is 20
Print value of variable
Ex:
name=“raj”
print "My name is %s “ % name) // %s will be replaced by value of variable name
Python Strings: : Format Specifiers
Sr.No Format Symbol & Conversion
1 %c character
2 %s string conversion via str() prior to formatting
3 %i signed decimal integer
4 %d signed decimal integer
5 %u unsigned decimal integer
6 %o octal integer
7 %x hexadecimal integer (lowercase letters)

8 %X hexadecimal integer (UPPERcase letters)

9 %e exponential notation (with lowercase 'e')

10 %E exponential notation (with UPPERcase 'E')

11 %f floating point real number


12 %g the shorter of %f and %e

13 %G the shorter of %f and %E


Python Strings: built in functions
1. len(s) function: calculates Length of string s
Ex: s=“hello” len(s) gives 5

2. lower(): Converts a string into lower case


Ex: s=“Hello” s.lower() gives ‘hello’

3. upper(): Converts a string into upper case


Ex: s=“Hello” s.upper() gives ‘HELLO’

4. split(separator_char): Splits the string at the specified separator, and returns a list
Ex: s=“hi all” s.split() gives list [‘hi’, ‘all’]

5. title(): Make the first letter in each word upper case


Ex: s=“hi all” s.title() gives “Hi All”

6. capitalize(): Upper case the first letter in this string


Ex: s=“hi all” s.capitalize() gives “Hi all”
Python Strings: built in functions
7. count(value): Return the number of times the value appears in the string
Ex: s=“hi how are you. Are you fine?” s.count(‘you’) gives 2

8. find(substring): if substring is present,returns the index where substring occurs. If not, returns -1
Ex: s=“hi how are you?” s.find(‘how’) gives 3, s.find(‘wel’) gives -1

9. join(): Joins the elements of an iterable to the end of the string


Ex: words=[‘I’, ‘am’, ‘learning’] s=‘ ‘.join(words) gives ‘I am learning’

10. replace(substring1,substring2): Replace substring1 by substring2 in original string


Ex: s=“I like mango” s.replace(‘mango’,’pineapple’) gives s=“I like pineapple”

11. strip(): removes leading and trailing spaces in a string


Ex: s=‘ hi hello ‘ s.strip() gives s=‘hi hello’

12. islower(): Returns True if all characters in the string are lower case
Ex: s=‘Hello’ s.islower() gives False
Python Strings: built in functions
13. center(space,pad_char): center align the string, using a specified character (space is default) as the fill character.
Ex: s=“welcome” s.center(10) gives ‘ welcome ’

8. find(substring): if substring is present,returns the index where substring occurs. If not, returns -1
Ex: s=“hi how are you?” s.find(‘how’) gives 3, s.find(‘wel’) gives -1

9. join(): Joins the elements of an iterable to the end of the string


Ex: words=[‘I’, ‘am’, ‘learning’] s=‘ ‘.join(words) gives ‘I am learning’

10. replace(substring1,substring2): Replace substring1 by substring2 in original string


Ex: s=“I like mango” s.replace(‘mango’,’pineapple’) gives s=“I like pineapple”

11. strip(): removes leading and trailing spaces in a string


Ex: s=‘ hi ‘ s.strip() gives s=‘hi’

12. islower(): Returns True if all characters in the string are lower case
Ex: s=‘hello’ s.islower() gives True
Python Strings: operations
1. String Concatenation: use + operator
S1=“hi”
S2=“hello”
S3=s1+s2 gives “hi hello”

2. Slicing : extract portion of string,


• use slice operator [startindex:endindex]
• Returns substring starting at startindex and ending at endindex-1.

Ex: s=“hi hello. How are you?”


S[0:2] gives “hi”
S[3:8] gives “hello”

S[:2] gives “hi” // if 1st index is omitted then it extracts from the beginning.
S[10:] gives “How are you” // if 2nd index is omitted then it extracts upto the end.
Python Strings: operations
Negative indexing: extract from the end

Ex: s=“hi hello. How are you?”

S[-5:-1] gives “you?”

S[-5:] gives “you?”

Escape Character: \ escapes characters from their reserved meaning.

Ex: s=‘ \\ ***\\welcome to DYPIU\\***\\’ gives output

\***\ welcome to DYPIU\***\


Assignment: check if string is palindrome or not
s=‘hello’

str_rev=s[::-1]

If s==str_rev:
print(“string is palindrome”)
Else:
print(“not palindrome”)
List
• Lists are used to store multiple items in a single variable.
• Store dissimilar type of data
• used to store collections of data
• ordered, mutable, and allow duplicate values
• Elements are referenced by index position.
• Index begins at 0. index of last element is 1- total no of elements in list

Ex. mylist = ["apple", 10, "banana", "cherry“, 4.5]


print(mylist)

Creating list:

Method1. Enlist elements in square brackets


e.g. fruits= ["apple", "banana", "cherry“]

Method2. use list() constructor function.


e.g. courses=list(“c”, “C++”, “Java”,”TCS”)
List
• Lists are used to store multiple items in a single variable.
• Store dissimilar type of data
• used to store collections of data
• ordered, mutable, and allow duplicate values
• Elements are referenced by index position.
• Index begins at 0. index of last element is 1- total no of elements in list

Ex. mylist = ["apple", 10, "banana", "cherry“, 4.5]


print(mylist)

Creating list:
Method1. Enlist elements in square brackets
e.g. fruits= ["apple", "banana", "cherry“]

Method2. use list() constructor function.


e.g. courses=list(“c”, “C++”, “Java”,”TCS”)
List indexing
Access list Items
List items are indexed and you can access them by referring to the index number:
courses=list(“c”, “C++”, “Java”,”TCS”)
positive Indexing
• positive indexing starts from the beginning.
• 0 refers to the first item, 1 refers to the second item etc.
Ex: courses[0] gives “c” , courses[1] gives “C++”

Negative Indexing
• Negative indexing starts from the end.
• -1 refers to the last item, -2 refers to the second last item etc.
• Ex: courses[-1] gives “TCS” , courses[-2] gives “Java” Range of Indexes

Range of Index
• You can specify a range of indexes by slice operator.
• All the values within the range will be returned.
• Ex: course[0:2] gives [“c”, “C++”]
List operations
Length of list
Syntax: len(listobject)
Ex: fruits = ["apple", "banana", "cherry"]
print(len(fruits))
Append Items
Syntax: listobject.append(item)
Ex: fruits.append(“guava”)

Remove Specified Item


Syntax: listobject.remove(item)
Ex: fruits.remove(“guava”)

Remove item at Specified Index


Syntax: listobject.pop(index)
Ex: fruits.pop(1) // item at index 1 will be removed

If index is not specified, then last item is removed.


fruits.pop() // last item will be removed
List operations
Count specific item in a list
Syntax: listobject.count(item)
Ex: fruits = ["apple", "banana", "cherry“, "apple"]
fruits.count(“apple”) gives 2
Clear list
Syntax: listobject.clear() // Removes all elements from the list
Ex: fruits.clear() gives []

Get index of Specified Item


Syntax: listobject.index(item)
Ex: fruits.index(“banana”) gives 1
fruits.index(“guava”) // error

insert item at Specified Index


Syntax: listobject.insert(index,item)
Ex: fruits.insert(1,”pineapple”) // insert “pineapple” at index 1
Gives ["apple", ”pineapple”,"banana", "cherry“, "apple"]
List operations
Sort List
Syntax: listobject.sort()
Ex1: fruits = ["apple", "cherry“, "banana"]
fruits.sort() // sorts alphabetically
gives ["apple", "banana“, "cherry“]
Ex2: numbers=[10,5,34,56,45]
numbers.sort() // sorts in ascending order
gives [5,10,34,45,56]
Ex2: numbers=[10,5,34,56,45]
numbers.sort(reverse=True) // sorts in descending order
gives [56,45,34,10,5]

Copy list
Syntax: listobject.copy()
Ex: fruitlist2=fruits.copy() // new list with same items is generated.
Join items of two Lists
Syntax: listobject1.extend(listobject2)
Ex: fruits.extend(numbers) gives ["apple", "cherry“, "banana“, 10,5,34,56,45]
List Traversal
Traverse a list: use loop

Ex1: fruits = ["apple", "cherry“, "banana"]

for x in fruits:
print(x)

Ex2: for each number in a list, print its square.


Numbers=[1,4,3,7]
for x in numbers:
print(x*x)
List Compehension
List comprehension offers a shorter syntax to create a new list based on the values of an existing list.

Ex: make the squares of numbers in a given list and store in another list.

numbers=[2,6,-16,4]
squares = [x*x for x in numbers]

Ex. Create a list containing only even numbers from another list
Even= [x for x in numbers if x%2==0]
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)] Dictionary
• Dictionaries are used to store data values in {key:value} pairs.
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]

• ordered,
[('brand', 'Ford'), ('model', 'Mustang'), ('year',
mutable 1964)]

• do not allow duplicates. No two keys can be the same.


Ex:
cars = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Accessing values in dictionary : accessed by using the key name
Ex: cars[“brand”] gives “Ford”
cars.get(“brand”) gives “Ford”
Access Keys
Syntax: dictobject.keys()
Ex: cars.keys() gives ['brand', 'model', 'year']
Access key, value pairs
Syntax: dictobject.items()
Ex: cars.items() gives
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)] Dictionary operations
Add[('brand',
item to 'Ford'),
dictionary :
('model', 'Mustang'), ('year', 1964)]

Method1. create
[('brand', new ('model',
'Ford'), key and'Mustang'),
assign value to 1964)]
('year', it.
Syntax: dictobject[“newkey”]=value
Ex: cars[“price”]= 1000000 // create price key and store value 1000000
Method2. use update() method. Provide {key:val} pair to update method.
Cars.update({“price”:1000000})

Change item value


Syntax: dictobject[key]=newvalue
Ex: cars[“price”]=1500000

Remove item with specific key


Syntax: dictobject.pop(keyname)
Ex: cars.pop(“price”) removes price key along with its value
Copy a Dictionary
Syntax: dictobject.copy()
Ex. Carscopy=cars.copy() // creates new dictionary carscopy with all the items in cars dictionary.
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)] Nested Dictionary
Disctionary inside other dictionary: uses multiple key levels to access values
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]

students ={
[('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]
“student1" : { 1. Print the name of student1
"name" : "Emili",
“PRN" : 12345, students[“student1”][“name”]
“gender”:”female”
2. Print info of all students
“grade” :”O”
}, For student in students:
“student2" : { print(students[student])
"name" : “akash",
“PRN" : 12346, 3. Print grade of student with PRN 12346
“gender”:”male”
for student in students:
“grade” :”O”
if students[student]["PRN"]==12347:
},
print(students[student]["grade"])
“student3" : {
"name" : “seema", 4. Add new student
“PRN" : 12347, stud={"name":"akanksha","PRN":12348,"gender":"female","grade" :"O"}
“gender”:”female” students.update({"student4":stud})
“grade” :”A”
}} 5. Delete student 3 record
students.pop("student3")

You might also like