Unit-III - Data Structures - Strings
Unit-III - Data Structures - Strings
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[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
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]
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 )
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 −
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
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
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
2 len(dict) Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
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
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
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
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""").
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.
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.
The casefold() method returns a string where all the characters are lower case.
'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å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
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 = "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
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.
end Optional. Where to end the search. Default is to the end of the string
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 ²
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()
x = txt.swapcase()
print(x)
x = txt.title()
print(x)
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'
65
Z
Comparing Strings
Using various relational operators the comparing of string is possible. Following
table illustrates it.
Operator Meaning
!= 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'
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.