Problem Solving using Python
(ITFC0101)
String
Dr. Naveen Kumar Gupta
Assistant Professor
Department of Information Technology
Dr B R Ambedkar National Institute of Technology Jalandhar
1
String
2
String
• Represents a sequence of characters
• Immutable data type:
• Once created a string, cannot change it
• Widely in many different applications,
• Storing and manipulating text data
• Representing names, addresses etc.
3
String Data Type
A collection of one or more characters put in a single, double, or triple quote
• Arrays of bytes representing Unicode characters
• In python: No character data type, a character is a string of length one
• Represented by str class
String Data Type
• String with Single Quote:
• Single quoted strings can
have double quotes inside
them, as in
'The knights who say "Ni!"'
String Data Type
String with Double Quote:
• Double quoted strings can
have Single quotes inside
them, as in
“I’m the best”
String Data Type
String with Triple Quote:
• Strings enclosed with three
occurrences of either quote symbol
• They can contain either
single or double quotes:
1. Using ''' '''
2. Using """ """
String Data Type
String with Triple Quote:
• Strings with multiple lines
Using triple quotes
1. Using ''' '''
2. Using """ """
String Data Type
>>> type("Hello, World!")
<class 'str’>
>>> type("17")
<class 'str’>
>>> type("3.2")
<class 'str’>
>>> 'This is a string.'
'This is a string.'
>>> """And so is this."""
'And so is this.’
String Data Type
>>> type('This is a string.')
<class 'str’>
>>> type("And so is this.")
<class 'str’>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str’>
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken!"
String Data Type
Triple quoted strings can even span multiple lines:
>>> message = """This message will
... span several
... lines."""
>>> print(message)
This message will
span several
lines.
>>>
String Data Type
• Python doesn’t care whether you use single or double quotes or the
three-of-a-kind quotes to surround strings
• Once it has parsed the text of your program or command
• The way it stores the value is identical in all cases
• Surrounding quotes are not part of the value
• When the interpreter wants to display a string
• It has to decide which quotes to use to make it look like a string
String Data Type
Accessing String Elements (characters)
• Individual characters of a String can be accessed by using Indexing
• Negative Indexing allows to access characters from the back of the String
• E.g. -1 refers to the last character
• -2 refers to the second last character, and so on.
Accessing the String Elements
Working with the parts of a string
• indexing operator
Length
• negative indices
Traversing a list
String Slices
Substring of a string
• Slicing: Extracting the string into smaller parts
• String Slicing: obtaining a sub-string from the given string
• Used to access a range of characters in the String
Python slicing can be done in two ways:
1. Using a slice() method
2. Using the list slicing [::] method (colon)
String Slices
Using slice() method
Syntax:
• slice(stop)
• slice(start, stop, step)
Returns a sliced object containing
elements in the given range only
Does not provide error message if
exceeding the value in slice
String Slices
Substring of a string
• Slice method basically works like range()
function
• Provides index values and steps
String Slices
Using List slicing or colon (:) method
An easy and convenient way to slice a string
Syntax:
arr[start : stop] # items start through stop-1
arr[ start : ] # items start through the rest of the elements
arr[ : stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr [start : stop : step] # start through not past stop, by step
String Slices
Substring of a string
• Does not provide error message if
exceeding the index value in slice
• Lasts up to last available letter
• Considers automatic index if not provided
String Slices
Substring of a string
String slicing
String Slices
Substring of a string
• Important Note: In case of colon (:)
• Includes the character at the start index
• Do not include the character at last
index
rd th th
3 and 4 position character added but not 5 one 🡪
• fruit[-4:-1] ?
Dealing with step count
28
• Write a program to reversing the string
• In one line only
• Use [::]
• [::-1]
29
Immutability
What is mutable?
• Mutable: Values can be changed after creation/declaration
30
String Immutability
• Immutability: Can not change the object after creation
31
Strings are immutable
you can’t change an existing string
• It will provide error message
Strings are immutable
I still want to change the string
Alternative Solution
• Create a new string
String comparison
Useful for putting words in lexicographical order
• <, >, <=, >=, !=, == operators are applicable
• Uppercase comes before lowercase
String comparison
== works on strings
Split() method
Syntax : str.split(separator, maxsplit)
Split() method
Syntax : str.split(separator, maxsplit)
• It splits a single multi-word string into a list of individual words, removing all
the whitespace between them.
Split() method
Syntax : str.split(separator, maxsplit)
• Use of separator
Split() method
Syntax: str.split(separator, maxsplit)
• maxsplit parameter:
control number of splits
• only do maximum that
number of splits as
defined by maxsplit
parameter
f-strings in Python
40
f-strings in Python
• Provide a concise and convenient way to
• Embed python expressions inside string literals for formatting
• Prefix the string with the letter “ f ”
• Supports simple expression evaluation
• Not supports all kind of expression evaluation
e.g., if-else, lambda etc.
41
f-strings in Python
42
f-strings in Python
• Provide a concise and
convenient way to
• Embed python expressions
inside string literals for
formatting
• Prefix the string with the letter
“f”
• Supports simple expression
evaluation
• Not supports all kind of
expression evaluation
43
f-strings in Python
• If f-string removed:
44
f-strings in Python
• Write simple valid python code
45
String Methods (1)
Method Description
capitalize() Converts the first character of the string to a capital (uppercase) letter
casefold() Implements caseless string matching
center() Pad the string with the specified character.
count() Returns the number of occurrences of a substring in the string.
encode() Encodes strings with the specified encoded scheme
endswith() Returns “True” if a string ends with the given suffix
expandtabs() Specifies the amount of space to be substituted with the “\t” symbol in the string
find() Returns the lowest index of the substring if it is found
format() Formats the string for printing it to console
format_map() Formats specified values in a string using a dictionary
46
String Methods (2)
Method Description
index() Returns the position of the first occurrence of a substring in a string
isalnum() Checks whether all the characters in a given string is alphanumeric or not
isalpha() Returns “True” if all characters in the string are alphabets
isdecimal() Returns true if all characters in a string are decimal
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
islower() Checks if all characters in the string are lowercase
isnumeric() Returns “True” if all characters in the string are numeric characters
isprintable() Returns “True” if all characters in the string are printable or the string is empty
isspace() Returns “True” if all characters in the string are whitespace characters
istitle() Returns “True” if the string is a title cased string
47
String Methods (3)
Method Description
isupper() Checks if all characters in the string are uppercase
join() Returns a concatenated String
ljust() Left aligns the string according to the width specified
lower() Converts all uppercase characters in a string into lowercase
lstrip() Returns the string with leading characters removed
maketrans() Returns a translation table
partition() Splits the string at the first occurrence of the separator
replace() Replaces all occurrences of a substring with another substring
rfind() Returns the highest index of the substring
rindex() Returns the highest index of the substring inside the string
rjust() Right aligns the string according to the width specified
48
String Methods (4)
Method Description
rpartition() Split the given string into three parts
rsplit() Split the string from the right by the specified separator
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
startswith() Returns “True” if a string starts with the given prefix
strip() Returns the string with both leading and trailing characters
swapcase() Converts all uppercase characters to lowercase and vice versa
title() Convert string to title case
translate() Modify string according to given translation mappings
upper() Converts all lowercase characters in a string into uppercase
zfill() Returns a copy of the string with ‘0’ characters padded to the left side of the string
49
Date & Time in Python
50
Date & Time in Python
current_time = datetime.datetime.now()
current_time.year
current_time.month
current_time.day
current_time.today()
current_time.hour
current_time.minute
current_time.second
current_time.microsecond
51
Lists as Arrays
Convert List to Python Array
52
Lists as Arrays
Convert List to Python Array
Need
• List may hold heterogeneous data types (can have data of multiple data types)
• Sometimes, it is undesirable
• Need to restrict the data elements to just one type
• Need to convert lists to a data structure that restricts the type of data i.e., array
53
Lists as Arrays
Ways to Convert List to Python Array
• array() method with data type indicator
• numpy.array() method
• numpy.asarray() method
54
Lists as Arrays
1. array() method with data type indicator
• Import desired library: from array import array
• pass the "data type" and the list to the function
Syntax: array(typecode, initializer)
Typecodes:
• Integer data-type 🡪 “i”
• Float data-type 🡪 “f”
• Double data-type 🡪 “d” and so on
55
Lists as Arrays
1. array() method with data type indicator
56
Lists as Arrays
Error: In case of non-compatible data item
57
Lists as Arrays
1. array() method: List of data type indicator
• 'b': Signed char (1 byte) - Stores small integers (range: -128 to 127).
• 'B': Unsigned char (1 byte) - Stores small positive integers (range: 0 to 255).
• 'u': Unicode character - Stores Unicode characters (not recommended in Python
3).
• 'h': Signed short (2 bytes) - Stores integers (range: -32,768 to 32,767).
• 'H': Unsigned short (2 bytes) - Stores positive integers (range: 0 to 65,535).
• 'i': Signed int (typically 4 bytes) - Stores standard integers.
• 'I': Unsigned int (typically 4 bytes) - Stores positive integers.
58
Lists as Arrays
1. array() method: List of data type indicator
• 'l': Signed long (4 bytes) - Stores long integers.
• 'L': Unsigned long (4 bytes) - Stores positive long integers.
• 'q': Signed long long (8 bytes) - Stores very large integers.
• 'Q': Unsigned long long (8 bytes) - Stores very large positive integers.
• 'f': Float (4 bytes) - Stores single-precision floating-point numbers.
• 'd': Double (8 bytes) - Stores double-precision floating-point numbers.
59
Lists as Arrays
2. numpy.array() method
• Import numpy module
• Syntax: np.array(list)
60
Lists as Arrays
With float data type
and automatic type
conversion
• 3 element ‘8’ is int
rd
and other float
• It is working fine with
addition operation
61
Lists as Arrays
automatic type
conversion in string
• If anyone element is
string 🡪 array will be
converted to string array
• Support operation with
individual element
• Not support operation
with all elements at once
62
Different copy of arrays
Both are representing
Different copy
63
Lists as Arrays
3. numpy.asarray() method: (as means replica)
• Syntax
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
• Convert input to an array
• Input can be:
• lists, lists of tuples
• tuples, tuples of tuples
• tuples of lists and arrays 64
65
Lists as Arrays
3. numpy.asarray() method
• Syntax
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
• order : Whether to use row-major or column-major (No visual Difference)
• 'C' for row-major (C-style) Default order
• 'F' for column-major (Fortran-style)
• dtype : data-type
66
Lists as Arrays
3. numpy.asarray() method
67
‘as’ means replica
Same copy of arrays
68
Sort an Array in Python
Method 1:
import numpy as np
sorted_arr = np.sort(arr)
Method 2:
sorted_arr = sorted(arr)
• Note: sort(list) method of list wouldn’t work with array
69
List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
70
Thank You!
71