KEMBAR78
Unit-III - Data Structures - Strings | PDF | String (Computer Science) | Character Encoding
0% found this document useful (0 votes)
15 views73 pages

Unit-III - Data Structures - Strings

Unit III covers data structures in Python, including lists, tuples, dictionaries, and strings. It details how to create, access, modify, and delete elements in these data structures, along with built-in functions and methods for each type. The document emphasizes the properties and operations of each collection type to aid in selecting the appropriate one for specific use cases.

Uploaded by

Shreya Sinkar
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)
15 views73 pages

Unit-III - Data Structures - Strings

Unit III covers data structures in Python, including lists, tuples, dictionaries, and strings. It details how to create, access, modify, and delete elements in these data structures, along with built-in functions and methods for each type. The document emphasizes the properties and operations of each collection type to aid in selecting the appropriate one for specific use cases.

Uploaded by

Shreya Sinkar
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/ 73

Unit-III

Data Structures & Strings


Unit III
Data Structures & Strings
Lists: Creating a list, accessing list elements, modifying list elements,
slicing in lists, list operations.

Tuple: Creating a tuple, working with a tuple, immutability, and tuple


operations.

Dictionary: Creating a dictionary, adding elements to a dictionary,


accessing elements of a dictionary, dictionary methods.

Strings : Operations On Strings, built in string functions, Immutability,


String Fomatting Operator, identity and membership operators, comparing
Strings,Iterating Strings.
Collection data type in python
There are four collection data types in the Python programming
language:
• List is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate
members.
• Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.

When choosing a collection type, it is useful to understand the properties


of that type.
List
The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that the items in a list need not be
of the same type.
Creating a list is as simple as putting different comma-separated values
between square brackets. For example −

list1 = ['physics', 'chemistry', 1997, 2000] Each element of a sequence is


assigned a number - its position or
list2 = [1, 2, 3, 4, 5 ] index. The first index is zero, the
list3 = ["a", "b", "c", "d"] second index is one, and so forth.
List
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with
the index or indices to obtain value available at that index.
For example −

list1 = ['physics', 'chemistry', 1997, 2000]


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

print ("list1[0]: ", list1[0])


print ("list2[1:5]: ", list2[1:5])

Output
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
List
Updating Lists
We can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and you can add to
elements in a list with the append() method.
For example −

list = ['physics', 'chemistry', 1997, 2000]


print ("Value available at index 2 : ", list[2])

list[2] = 2001
print ("New value available at index 2 : ", list[2])
Output
Value available at index 2 : 1997
New value available at index 2 : 2001
List
Delete List Elements
To remove a list element, you can use either
the del statement if you know exactly which element(s) you
are deleting. you can use the remove() method if you do not
know exactly which items to delete. For example −
list = ['physics', 'chemistry', 1997, 2000]
print (list)

del list[2]
print ("After deleting value at index 2 : ", list)
Output
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000
List
Basic List Operations

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1,2,3] : print 123 Iteration
(x,end = ' ')
List
Indexing, Slicing and Matrixes
L = ['C++'', 'Java', 'Python']

Python Expression Results Description


L[2] 'Python' Offsets start at zero
L[-2] 'Java' Negative: count from the right
L[1:] ['Java', 'Python'] Slicing fetches sections
List
Built-in List Functions and Methods

Sr. No. Function & Description


1 cmp(list1, list2) This method returns 0 if both list are equal, -1 if list1 <
list2 and 1 if list1 > list2..
2 len(list) Gives the total length of the list.
3 max(list) Returns item from the list with max value.
4 min(list) Returns item from the list with min value.
5 list(seq) Converts a tuple into list.
List
Built-in List Functions (Example)
list1 = [134, 738, 3647, 378]
print (len(list1))

list2 = list(range(5)) #creates list of numbers between 0-4


print (len(list2))
print ("Max value element : ", max(list1))
print ("Max value element : ", min(list1))

Tuple = (123, 'C++', 'Java', 'Python')


list1 = list(Tuple)
print ("List elements : ", list1)
Output
4
5
Max value element : 3647
Max value element : 134
List elements : [123, 'C++', 'Java', 'Python']
List
Built-in List Methods

Sr. No. Methods & Description


1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index, obj) Inserts object obj into list at offset index
6 list.pop(obj = list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort([func]) Sorts objects of list, use compare func if given
List
Built-in List Methods (Example)
#python different methods
list1 = ['C++', 'Java', 'Python',123,123]
list1.append('C#')
print ("Updated list : ", list1)

print ("Count for 123 : ", list1.count(123))


list2 = list(range(5))

list1.extend(list2)
print ('Extended List :', list1)
print ('Index of Java', list1.index('Java'))
Output
print ('Index of Python', list1.index('Python'))

list1.insert(1, 'Biology') Updated list : ['C++', 'Java', 'Python', 123, 123, 'C#']
print ('Final list : ', list1)
Count for 123 : 2
list1.pop()
print ("list now : ", list1) Extended List : ['C++', 'Java', 'Python', 123, 123, 'C#', 0, 1, 2, 3, 4]
list1.pop(2)
print ("list now : ", list1) Index of Java 1
Index of Python 2
list1.remove('Biology')
print ("list now : ", list1) Final list : ['C++', 'Biology', 'Java', 'Python', 123, 123, 'C#', 0, 1, 2, 3, 4]
list now : ['C++', 'Biology', 'Java', 'Python', 123, 123, 'C#', 0, 1, 2, 3]
list1.reverse()
print ("list now : ", list1) list now : ['C++', 'Biology', 'Python', 123, 123, 'C#', 0, 1, 2, 3]

list3=[5,6,2,3,8,9,1] list now : ['C++', 'Python', 123, 123, 'C#', 0, 1, 2, 3]


list3.sort()
print ("list now : ", list3) list now : [3, 2, 1, 0, 'C#', 123, 123, 'Python', 'C++']

list4=['G','A','B','P','T','Y'] list now : [1, 2, 3, 5, 6, 8, 9]


list4.sort()
print ("list now : ", list4) list now : ['A', 'B', 'G', 'P', 'T', 'Y']
Tuple
Tuples are sequences, just like lists. The main difference between the
tuples and the lists is that the tuples cannot be changed unlike lists.
Tuples use parentheses, whereas lists use square brackets.

For example
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Tuple
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain the value available at that index.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])


print ("tup2[1:5]: ", tup2[1:5])

Output :
tup1[0]: physics
tup2[1:5]: (2, 3, 4,
5)
Tuple
Updating Tuples
Tuples are immutable, which means you cannot update or change the
values of tuple elements. You are able to take portions of the existing
tuples to create new tuples as the following example demonstrates −

tup1 = (12, 34.56)


tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)

Output :
(12, 34.56, 'abc', 'xyz')
Tuple
Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course,
nothing wrong with putting together another tuple with the undesired
elements discarded.
To explicitly remove an entire tuple, just use the del statement.
For example −
tup = ('physics', 'chemistry', 1997, 2000)
print (tup)
del tup
print ("After deleting tup : ")
print (tup) ('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in
Output : <module>
print tup;NameError:
name 'tup' is not defined
Tuple
Basic Tuples Operations

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1,2,3) : 123 Iteration
print (x, end = ' ')
Tuple
Built-in Tuple Functions

Sr. No. Function & Description


1 cmp(tuple1, tuple2) This method returns 0 if both tuples are
equal, -1 if tuple1 < tuple2 and 1 if tuple > tuple..
2 len(tuple) Gives the total length of the tuple.
3 max(tuple) Returns item from the tuple with max value.
4 min(tuple) Returns item from the tuple with min value.
5 tuple(seq) Converts a list into tuple.
Tuple
Built-in Tuple Functions (Example)
tuple1, tuple2 = (123, 786, 546), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))

print ("Max value element : ", max(tuple1))


print ("min value element : ", min(tuple1))

list1 = ['maths', 'che', 'phy', 'bio']


tuple1 = tuple(list1)
print ("tuple elements : ", tuple1)

Output :
First tuple length : 3
Second tuple length : 2
Max value element : 786
min value element : 123
tuple elements : ('maths', 'che', 'phy', 'bio')
Dictionary
• A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets, and they
have keys and values.
• Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces {
}.
• Keys are unique within a dictionary while values may not be. The
values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Dictionary
Accessing Values in Dictionary
To access dictionary elements, You can access the items of a dictionary by
referring to its key name, inside square brackets:

Example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

Output :
dict['Name']:
Zara dict['Age']: 7
Dictionary
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown in a
simple example given below.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])


print ("dict['School']: ", dict['School'])
Print (dict)

Output :
dict['Age']: 8
dict['School']: DPS School
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'DPS School'}
Dictionary
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
operation.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output :
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is
unsubscriptable
Dictionary
Built-in Dictionary Functions

Sr. No. Function & Description

1 cmp(dict1, dict2) This method returns 0 if both dictionaries are equal, -1 if


dict1 < dict2 and 1 if dict1 > dic2.

2 len(dict) Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

3 str(dict) Produces a printable string representation of a dictionary

4 type(variable) Returns the type of the passed variable. If passed variable is


dictionary, then it would return a dictionary type.
Dictionary
Built-in Dictionary Functions (Example)
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

print ("Length : %d" % len (dict))

print ("Equivalent String : %s" % str (dict))

print ("Variable Type : %s" % type (dict))

Output :
Length : 3
Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Variable Type : <class 'dict'>
Dictionary
Built-in Dictionary Methods
Sr. No. Method & Description
1 dict.clear() Removes all elements of dictionary dict
2 dict.copy() Returns a shallow copy of dictionary dict
3 dict.fromkeys() Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None) For key key, returns value or default if key not in dictionary

5 dict.has_key(key) Removed, use the in operation instead.


6 dict.items() Returns a list of dict's (key, value) tuple pairs
7 dict.keys() Returns list of dictionary dict's keys
8 dict.setdefault(key, default = None) Similar to get(), but will set dict[key] = default if key is
not already in dict
9 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict
10 dict.values() Returns list of dictionary dict's values
Dictionary
Built-in Dictionary Methods (Example)
clear() : The method clear() removes all items from the dictionary.

Example:
dict = {'Name': 'Zara', 'Age': 7}
print ("Start Len : %d" % len(dict))
dict.clear()
print ("End Len : %d" % len(dict))
Output:
Start Len : 2End Len : 0

copy(): The method copy() returns a shallow copy of the dictionary.

Example:
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
Output:
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Dictionary
Built-in Dictionary Methods (Example)
fromkeys(): The method fromkeys() creates a new dictionary with keys
from seq and values set to value.
Example:
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict))
Output:
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

get(): The method get() returns a value for the given key. If key is
not available then returns default value None.
Example:
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
Output:
Value : 27
Value : NA
Dictionary
Built-in Dictionary Methods (Example)
has_key() : The method has_key() returns true if a given key is
available in the dictionary, otherwise it returns a false.
Example:
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.has_key('Age'))
print ("Value : %s" % dict.has_key('Sex'))
Output:
Value : True
Value : False

items() : The method items() returns a list of dict's (key, value)


tuple pairs.
Example:
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
Output: Value : [('Age', 7), ('Name', 'Zara')]
Dictionary
Built-in Dictionary Methods (Example)
keys() : The method keys() returns a list of all the available keys
in the dictionary.
Example:
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())
Output:
Value : dict_keys(['Age', 'Name'])

setdefault(): The method setdefault() is similar to get(), but will


set dict[key] = default if key is not already in dict.
Example:
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None))
print ("Value : %s" % dict.setdefault('Sex', None))
print (dict)
Output:
Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}
Dictionary
Built-in Dictionary Methods (Example)
update(): The method update() adds dictionary dict2's key-values
pairs in to dict. This function does not return anything.
Example:
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("updated dict : ", dict)
Output:
updated dict : {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}

values(): The method values() returns a list of all the values


available in a given dictionary.
Example:
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print ("Values : ", list(dict.values()))
Output:
Values : ['female', 7, 'Zara']
Escape Sequence in Python
Escape Sequence Description Example

Example:
print("line1 \
line2 \
\newline Backslash and newline ignored line3")
Output:
line1 line2 line3
Example:
print("\\")
\\ Backslash (\) Output:
\
Example:
print('\'')
\' Single quote (') Output:
'
Example:
print("\"")
\" Double quote (") Output:

Example:
print("Hello \b World!")
\b ASCII Backspace (BS) Output:
Hello World!
Example:
print("Hello \t World!")
\t ASCII Horizontal Tab (TAB) Output:
Hello World!
Example:
print("Hello \v World!")
\v ASCII Vertical Tab (VT) Output:
Hello
World!
Python - String
• A string object is one of the sequence data types in Python. It is an immutable
sequence of Unicode characters. Strings are objects of Python's built-in class 'str'.
• String literals are written by enclosing a sequence of characters in single quotes
('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").

Example1: Example2: Example3:

str1='hello' str1="hello" str1='''hello'''


print(str1) print(str1) print(str1)

Output: Output: Output:


hello hello hello
Python - String
• A sequence is defined as an ordered collection of items. Hence, a string is an
ordered collection of characters. The sequence uses an index (starting with zero) to
fetch a certain item (a character in case of a string) from it.

Example:

myString='hello'
print(myString[0]) h e l l o \0
print(myString[1]) 0 1 2 3 4 5
print( myString[4])

Output:
h
e
o
Python - String
• The string is an immutable object. Hence, it is not possible to modify it. The attempt
to assign different characters at a certain index results in errors.

Example:
myString='hello'
myString[1]='a'
Output:
TypeError: 'str' object does not support item assignment
Python - String
Triple Quoted String
The triple quoted string is useful when a multi-line text is to be defined as a string literal.
myString="""Welcome to
Python Tutorial
from TutorialsTeacher"""
myString
Output:
'Welcome to Python Tutorial from TutorialsTeacher'
Escape Sequences
Following table is a list of escape or non-printable characters that can be represented
with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted
strings.
Character Use
\a alert
\b backspace
\cx Control X
\e escape
\f Form feed
\n New line or next line
\r carriage return
\s space
\t tab
\v Vertical Tab
Cont…
String Operators
Obviously, arithmetic operators don't operate on strings. However, there are special
operators for string processing.

Operator Operation Description Example


a='hello'
Concatenation Appends the second string b='world'
+
or Appending to the first a+b
'helloworld'
a='hello'
Multiple copies of the same
* Multiplying a*3
string
'hellohellohello'
a = 'Python Tutorials'
Returns the character at the
[] Indexing a[7]
given index
T
Fetches the characters in
a = 'Python Tutorials'
the range specified by two
[:] Slicing a[7:15]
index operands separated
'Tutorial'
by the : symbol
Cont…
String Operators
Operator Description Example
Returns true if a character exists in the a = 'Python Tutorials'
given string 'X' in a
False
in 'Python' in a
True
'python' in a
False
Returns true if a character does not exist in a = 'Python Tutorials'
the given string 'X' not in a
not in True
'Python' not in a
False
String Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.

Example:
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character

Hello World!
H
Output: llo
llo World!
String Length
To get the length of a string, use the len() function.
Example:

a = "Hello, World!"
print(len(a))
Output:
13
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.

In the following example, name is a string and age is an integer variable. Their values are
inserted in the string with %s and %d format specification symbols, respectively. These symbols
are interpolated to values in a tuple with the % operator in front.

#You can have multiple parameters too.


Example: Example:
name="Bond" name="Bond"
"My name is %s." % name age=30
"My name is %s and age is %d years." % (name, age)
Output:
'My name is Bond.' Output:
'My name is Bond and age is 30 years.'
String Formatting
All C style format specification symbols are permitted.

Format Symbol Conversion


%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x / %X hexadecimal integer (lowercase letters)
%e / %E exponential notation (with lowercase 'e')
%f floating point real number
Built-in String Methods
The capitalize() method returns a string where the first character is upper case.

txt = "hello, and welcome to my world."


x = txt.capitalize()
print (x)

Hello, and welcome to my world.

The casefold() method returns a string where all the characters are lower case.

txt = "Hello, And Welcome To My World!"


x = txt.casefold()
print(x)

hello, and welcome to my world!


Built-in String Methods
The encode() method encodes the string, using the specified encoding. If no encoding is
specified, UTF-8 (Unicode Transformation Format) will be used.
Syntax
string.encode(encoding=encoding, errors=errors)
Parameter Values
Parameter Description
encoding Optional. A String specifying the encoding to use. Default is UTF-8
errors Optional. A String specifying the error method. Legal values are:

'backslashreplace' - uses a backslash instead of the character that could not be encoded
'ignore' - ignores the characters that cannot be encoded
'namereplace' - replaces the character with a text explaining the character
'strict' - Default, raises an error on failure
'replace' - replaces the character with a questionmark
'xmlcharrefreplace' - replaces the character with an xml character
Built-in String Methods
txt = "My name is Ståle"

print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace")
)
print(txt.encode(encoding="ascii",errors="strict"))
b'My name is St\\xe5le'
b'My name is Stle'
b'My name is St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le'
b'My name is St?le'
b'My name is St&#229;le'

----> 8 print(txt.encode(encoding="ascii",errors="strict"))
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5'
in position 13: ordinal not in range(128)
Built-in String Methods
The center() method will center align the string, using a specified character
(space is default) as the fill character.
Syntax
string.center(length, character)
Parameter Values
Parameter Description
length Required. The length of the returned string
character Optional. The character to fill the missing space on each side. Default is " " (space)

txt = ”apple"
x = txt.center(20,"O")
print(x)
OOOOOOOappleOOOOOOO
Built-in String Methods
The count() method returns the number of times a specified value appears in the
string.
Syntax
string.count(value, start, end)
Parameter Values
Parameter Description
value Required. A String. The string to value to search for
start Optional. An Integer. The position to start the search. Default is 0
end Optional. An Integer. The position to end the search. Default is the end of the string

txt = "I love apples, apple are my favorite fruit"


x = txt.count("apple“,10, 24)
print(x)

1
Built-in String Methods
The endswith() method returns True if the string ends with the specified value,
otherwise False.
Syntax
string.endswith(value, start, end)
Parameter Values
Parameter Description
value Required. The value to check if the string ends with
start Optional. An Integer specifying at which position to start the search
end Optional. An Integer specifying at which position to end the search

txt = "Hello, welcome to my world."


x = txt.endswith("my world.", 5, 11)
print(x)
False
Built-in String Methods
The expandtabs() method sets the tab size to the specified number of whitespaces.
Syntax
string.exandtabs(tabsize)
Parameter Values
Parameter Description
tabsize Optional. A number specifying the tabsize. Default tabsize is 8

txt = "H\te\tl\tl\to"
print(txt)
print(txt.expandtabs())
print(txt.expandtabs(2))
print(txt.expandtabs(4))
print(txt.expandtabs(10))

H e l l o
H e l l o
H e l l o
H e l l o
H e l l o
Built-in String Methods
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.
Syntax
string.find(value, start, end)
Parameter Values

Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string

txt = "Hello, welcome to my world."


x = txt.find("e", 5, 10)
print(x)

8
Built-in String Methods
• The format() method formats the specified value(s) and insert them inside the
string's placeholder.
• The placeholder is defined using curly brackets: {}. Read more about the
placeholders in the Placeholder section below.
• The format() method returns the formatted string.

txt1 = "My name is {fname}, I'am {age}".format(fname


= "John", age = 36)
txt2 = "My name is {0}, I'am {1}".format("John",36)
txt3 = "My name is {}, I'am {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)

My name is John, I'am 36


My name is John, I'am 36
My name is John, I'am 36
Built-in String Methods
Formatting Types Inside the placeholders you can add a formatting type to format the result:
:< Left aligns the result (within the available space)
:> Right aligns the result (within the available space)
:^ Center aligns the result (within the available space)
:= Places the sign to the left most position
:+ Use a plus sign to indicate if the result is positive or negative
:- Use a minus sign for negative values only
: Use a space to insert an extra space before positive numbers (and a minus sign befor negative numbers)
:, Use a comma as a thousand separator
:_ Use a underscore as a thousand separator
:b Binary format
:c Converts the value into the corresponding unicode character
:d Decimal format
:e Scientific format, with a lower case e
:E Scientific format, with an upper case E
:f Fix point number format
:F Fix point number format, in uppercase format (show inf and nan as INF and NAN)
:g General format
:G General format (using a upper case E for scientific notations)
:o Octal format
:x Hex format, lower case
:X Hex format, upper case
:n Number format
:% Percentage format
Built-in String Methods
• The index() method finds the first occurrence of the specified value.
• The index() method raises an exception if the value is not found.
• The index() method is almost the same as the find() method, the only difference is
that the find() method returns -1 if the value is not found.
Syntax
string.index(value, start, end)
Parameter Values
Parameter Description

value Required. The value to search for

start Optional. Where to start the search. Default is 0

end Optional. Where to end the search. Default is to the end of the string

txt = "Hello, welcome to my world."


x = txt.index("e", 5, 10)
print(x)

8
Built-in String Methods
• The isalnum() method returns True if all the characters are alphanumeric, meaning
alphabet letter (a-z) and numbers (0-9).
• Example of characters that are not alphanumeric: (space)!#%&? etc.
Syntax
string.isalnum()
txt = "Company 12"
x = txt.isalnum()
print(x)
False
Built-in String Methods
• The isalpha() method returns True if all the characters are alphabet letters (a-z).
• Example of characters that are not alphabet letters: (space)!#%&? etc.
Syntax
string.isalpha()
txt = "Company10"
x = txt.isalpha()
print(x)
False
• The isdecimal() method returns True if all the characters are decimals (0-9).
• This method is used on unicode objects.
Syntax
string.isdecimal()
a = "\u0030" #unicode for 0
b = "\u0047" #unicode for G
print(a.isdecimal())
print(b.isdecimal())
True
False
Built-in String Methods
• The isdigit() method returns True if all the characters are digits, otherwise False.
• Exponents, like ², are also considered to be a digit.
Syntax
string.isdigit()
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
print(a.isdigit())
print(b.isdigit())
True
True
Built-in String Methods
• The isidentifier() method returns True if the string is a valid identifier, otherwise
False.
• A string is considered a valid identifier if it only contains alphanumeric letters
(a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number,
or contain any spaces.
Syntax
string.isidentifier()
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"
print(a.isidentifier())
print(b.isidentifier())
print(c.isidentifier())
print(d.isidentifier())
True
True
False
False
Built-in String Methods
• The islower() method returns True if all the characters are in lower case, otherwise False.
• Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax
string.islower()
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"
print(a.islower())
print(b.islower())
print(c.islower())
False
True
False
Built-in String Methods
• The isnumeric() method returns True if all the characters are numeric (0-9), otherwise
False.
• Exponents, like ² and ¾ are also considered to be numeric values.
Syntax
string.isnumeric()
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for &sup2;
c = "10km2"
print(a.isnumeric())
print(b.isnumeric())
print(c.isnumeric())

True
True
False
Built-in String Methods
• The isupper() method returns True if all the characters are in upper case,
otherwise False.
• Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax
string.isupper()
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"

print(a.isupper())
print(b.isupper())
print(c.isupper())

False
False
True
Built-in String Methods
The lower() method returns a string where all characters are lower case.
Symbols and Numbers are ignored.
Syntax
string.lower()
txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
hello my friends
Built-in String Methods
The replace() method replaces a specified phrase with another specified phrase.
Syntax
string.replace(oldvalue, newvalue, count)
Parameter Values
Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace.
Default is all occurrences

txt = "one one was a king, two two was one too."
x = txt.replace("one", "three")
print(x)
three three was a king, two two was three too.
Built-in String Methods
The swapcase() method returns a string where all the upper case letters are lower
case and vice versa.
Syntax
string.swapcase()

txt = "Hello My Name Is PETER"

x = txt.swapcase()

print(x)

hELLO mY nAME iS peter


Built-in String Methods
• The title() method returns a string where the first character in every word is upper
case. Like a header, or a title.
• If the word contains a number or a symbol, the first letter after that will be
converted to upper case.
Syntax
string.title()
txt = "Welcome to my 2nd world"

x = txt.title()

print(x)

Welcome To My 2Nd World


Built-in String Methods
• The upper() method returns a string where all characters are in upper case.
• Symbols and Numbers are ignored.
Syntax
string.upper()

txt = "Hello my friends"

x = txt.upper()

print(x)

HELLO MY FRIENDS
ord() and chr() Functions
The ord() function returns the ASCII code of the character and chr() function return
character represented by ASCII code. For example

a='A'

print(ord(a)) # Return the ASCII code of character A

print(chr(90))# Return the character of the ASCII code 90

65
Z
Comparing Strings
Using various relational operators the comparing of string is possible. Following
table illustrates it.
Operator Meaning

== If two values are equal then condition becomes true.

!= If two strings are not equal then the condition become true

< This is less than operator. If left string is less than the right string then the return values is
true.

> This is greater than operator. If left string is greater than the right string then the return
values is true.

<= This is less than equal to operator. If left string is less than the right string or equal to right
string then the return values is true.

>= This is greater than equal to operator. If left string is greater than the right string or equal
to right string then the return values is true.
Comparing Strings

fruit1 = 'Apple'

print(fruit1 == 'Apple') True


print(fruit1 != 'Apple') False
print(fruit1 < 'Apple') False
print(fruit1 > 'Apple') False
print(fruit1 <= 'Apple') True
print(fruit1 >= 'Apple') True
Iterating Strings
We can traverse the string using the for loop or using the while loop
for letter in 'Python': # First Example
print ("Current Letter :", letter)

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print ("Current fruit :", fruit)

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Assignment No. 3
1. What is meaning of statement "strings are immutable"?
2. How to concatenate two strings?
3. How to format string?
4. Explain various ways of iterating a string.
5. Explain ord() and chr() function of string.
6. what are membership operators of a string?
7. Take two strings and compare them using relational operators.
8. Explain any four in built functions of string.

You might also like