Chapter 30 - Strings in Python
- Authors
- Ms. Samavi Salman
- Dr. Rao Muhammad Adeel Nawab
- Supporting Material
Quick Recap
- Quick Recap – Arrays in Python
In previous Chapter, I presented
- Array
- An Array (a.k.a. Subscripted Variable) is defined as a collective name assigned to a group of similar quantities
- Array vs Array Element
- Array
- is a collection of Array Elements
- Array Element
- Array Element is an individual member of an Array
- Accessing Array vs Accessing Array Element
- Accessing Array
- Use name of Array
- Accessing Array Element
- Use name of Array[Subscript] OR name of Array[Index]
- Accessing Array
- Array
- Array Element vs Normal Variable
- Each Array Element behaves like a Normal Variable i.e.,
- All Operations that we can perform on a Normal Variable can also be performed on an Array Element
- Each Array Element behaves like a Normal Variable i.e.,
- Methods to Store Values in an Array
- The three main Methods to Store Values in an Array are
- Method 1: Array Initialization
- Method 2: Store Values Element by Element at Code Time
- Method 3: Store Values Element by Element at Run Time
- The three main Methods to Store Values in an Array are
- Methods to Store Values in an Array
- The two main Methods to Display Values Stored in an Array are
- Method 1: Display Values Stored in an Array without Loop
- Method 2: Display Values Stored in an Array with Loop
- Method 3: Display Entire Array at Once
- The two main Methods to Display Values Stored in an Array are
Basics of Strings
- String
- Definition
- A string is defined as a sequence of characters
- Note
- A string is an array of characters
- String Methods
- Definition
- String Methods are special functions used to manipulate strings
- Purpose
- The main purpose of String Methods is to
- Perform various operations on Real-world data stored in the form of Strings to perform various useful Real-world Tasks
- The main purpose of String Methods is to
- String Literals
- Definition
- In Python, String Literals are surrounded by either single quotes, or double quotes, or triple quotes
- Delimiters
- The quotes surrounding a string are called delimiters
- Purpose of Delimiters
- The purpose of delimiters is to tell Python
- where a string begins and where it ends
- Note
- If one type of quotes is used as delimiters the other types of quotes can be used inside a string
- The purpose of delimiters is to tell Python
- Single Quote, Double Quote and Triple Quote
- Single Quote
- In Python, Single Quotes are generally used for String Literals and Regular Expressions
- Double Quote
- In Python, Double Quotes are generally used for string representation
- Triple Quote
- In Python, Triple Quotes are generally used to allow strings to span multiple lines (which may include tabs, newlines, or any other special characters)
- Escape Sequences
- Definition
- An Escape Sequence is defined using a combination of two characters, were
- First Character is a Backslash \ and
- Second Character is a Letter
- An Escape Sequence is defined using a combination of two characters, were
- Purpose
- The main purpose of the Escape Sequences is to
- add Special Characters and
- handle complex Formatting
- The main purpose of the Escape Sequences is to
- Main Escape Sequences in Python
- In Python Code, Character \ and Character(s) following it are replaced with
- A Single Character
- Some of the popular and widely used Escape Sequences of Python Programming Language are as follows
- New Line (\n)
- In Python Code, Two Characters \n is replaced with
- Newline
- In Python Code, Two Characters \n is replaced with
- Tab (\t)
- In Python Code, Two Characters \t is replaced with
- Tab
- In Python Code, Two Characters \t is replaced with
- Carriage Return (\r)
- In Python Code, Two Characters \r is replaced with
- Resets a Cursor to the Beginning of a Line of Text
- In Python Code, Two Characters \r is replaced with
- Single Quote (\‘)
- In Python Code, Two Characters \’ is replaced with
- ‘
- In Python Code, Two Characters \’ is replaced with
- Double Quotes (\“)
- In Python Code, Two Characters \” is replaced with
- “
- In Python Code, Two Characters \” is replaced with
- Backslash (\\)
- In Python Code, Two Characters \\ is replaced with
- \
- In Python Code, Two Characters \\ is replaced with
- Triple Quotes (\“””)
- In Python Code, Two Characters \“”” is replaced with
- “””
- In Python Code, Two Characters \“”” is replaced with
- New Line (\n)
- Calculate Length of a String
- Length of a String
- Length of a String is defined as the total number of characters contained in a string, including spaces
- Function to Calculate Length of a String
- len()
- Syntax
- len(object)
- Purpose
- The purpose of len() Function is to
- calculate length of a given string
- The purpose of len() Function is to
- Example 1 - Strings in Single Quote, Double Quote and Triple Quote
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Create Strings using Single, Double and Triple Quotes
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to create a string using single, double, and triple quotes
'''
# Input + Processing + Output
try:
# Using Single Quotes
print('---Message with Single Quotes---')
print('Allah is One.')
# Using Double Quotes
print("")
print('---Message with Double Quotes---')
print("Allah is One. He's the creator of heavens and earth.")
# Using Triple Quotes
print("")
print('---Message with Triple Quotes---')
print('''Allah is One.
He's the creator of heavens and earth.
He has "control" over everything.''')
print("")
# Calculating Length of String with Single Quotes using len() Function
print('---Length of String with Single Quotes---')
print('Length of "Allah is One." is: ', len("Allah is One."))
print("")
# Calculating Length of String with Double Quotes using len() Function
print('---Length of String with Double Quotes---')
print("Length of 'Allah is One. He's the creator of heavens and earth.' is: ", len("Allah is One. He's the creator of heavens and earth."))
print("")
# Calculating Length of String with Triple Quotes using len() Function
print('---Length of String with Triple Quotes---')
print('''Length of 'Allah is One.
He's the creator of heavens and earth.
He has 'control' over everything.' is: ''', len("Allah is One. He's the creator of heavens and earth. He has 'control' over everything."))
except:
print('Error Occurred')
---Message with Single Quotes---
Allah is One.
---Message with Double Quotes---
Allah is One. He's the creator of heavens and earth.
---Message with Triple Quotes---
Allah is One.
He's the creator of heavens and earth.
He has "control" over everything.
---Length of String with Single Quotes---
Length of "Allah is One." is: 13
---Length of String with Double Quotes---
Length of 'Allah is One. He's the creator of heavens and earth.' is: 52
---Length of String with Triple Quotes---
Length of 'Allah is One.
He's the creator of heavens and earth.
He has 'control' over everything.' is: 86
TODO and Your Turn
TODO Task 1
- Task
- Consider the following Strings and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. |
String 2 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. He’s (PBUH) role model for us in all fields of life. |
String 3 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. He’s (PBUH) role model for us in all fields of life. One who doesn’t accept Hazrat Muhammad (PBUH) as the last Messenger of Allah is a non-Muslim. |
- Questions
- Print String 1 using Single Quotes, String 2 using Double Quotes and String 3 using Triple Quotes
- Print lengths of String 1, String 2, and String 3 using len() Function
Your Turn Task 1
- Task
- Consider three Strings (similar to the ones given in the TODO Task) and answer the questions given below.
- Questions
- Print String 1 using Single Quotes, String 2 using Double Quotes and String 3 using Triple Quotes
- Print lengths of String 1, String 2, and String 3 using len() Function
Creating a String
- Creating a String
- Definition
- In Python, generally a String is created using double quotes
- Note
- In Python, we can create Strings using single quotes, double quotes, and triple quotes
- Check Data Type of a Variable
- Purpose to Check Data Type of a Variable
- To understand what type of information (data) is stored in a Variable, we need to check its Data Type
- Function to Check Data Type of a Variable
- type()
- Syntax
- type(object)
- Purpose
- The purpose of type() Function is to
- check the type of data stored in a variable
- The purpose of type() Function is to
- Methods to Create a String
- In Sha Allah, in next Slides, I will present three methods to create a String
- Method 1: Create a String using Single Quotes
- Method 2: Create a String using Double Quotes
- Method 3: Create a String using Triple Quotes
- Example 1 – Creating a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Create Strings
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to create a string using single quotes
'''
# Input + Processing + Output
try:
# Creating a string using single quotes
print("---Creating a String using Single Quote---")
message_1 = 'Allah is One.'
print("message_1 = "+ message_1)
print("Length of message_1 =", len(message_1))
print("Data Type of message_1 =", type(message_1))
print("")
# Creating a string using double quotes
print("---Creating a String using Double Quote---")
message_2 = "Allah is One. He's the creator of heavens and earth."
print("message_2 = "+ message_2)
print("Length of message_2 =", len(message_2))
print("Data Type of message_2 =", type(message_2))
print("")
# Creating a string using triple quotes
print("---Creating a String using Triple Quote---")
message_3 = '''Allah is One. He's the creator of heavens and earth.
He has "control" over everything.'''
print("message_3 = "+ message_3)
print("Length of message_3 =", len(message_3))
print("Data Type of message_3 =", type(message_3))
print("")
except:
print('Error Occurred')
---Creating a String using Single Quote---
message_1 = Allah is One.
Length of message_1 = 13
Data Type of message_1 =
---Creating a String using Double Quote---
message_2 = Allah is One. He's the creator of heavens and earth.
Length of message_2 = 52
Data Type of message_2 =
---Creating a String using Triple Quote---
message_3 = Allah is One. He's the creator of heavens and earth.
He has "control" over everything.
Length of message_3 = 91
Data Type of message_3 =
TODO and Your Turn
TODO Task 1
- Task
- Consider the following Strings and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. |
String 2 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. He’s (PBUH) role model for us in all fields of life. |
String 3 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. He’s (PBUH) role model for us in all fields of life. One who doesn’t accept Hazrat Muhammad (PBUH) as the last Messenger of Allah is a non-Muslim. |
- Questions
- Print String 1 using Single Quotes, String 2 using Double Quotes and String 3 using Triple Quotes
- Print lengths and types of String 1, String 2, and String 3 using len() Function
Your Turn Task 1
- Task
- Consider three Strings (similar to the ones given in the TODO Task) and answer the questions given below.
- Questions
- Create String 1 using Single Quotes, String 2 using Double Quotes and String 3 using Triple Quotes
- Print length and types of String 1, String 2, and String 3 using len() Function
Formatting a String
- Formatting a String
- In Sha Allah, in next Slides, I will present following functions to format a String
- title()
- capitalize()
- upper()
- lower()
- center()
- title() Function
- Function Name
- title()
- Syntax
string.title()
- Purpose
- The main purpose of title() function is to
- capitalize the first character of each word in a String
- The main purpose of title() function is to
- Popular Use Case
- Heading
- Note
- The title() Function ignores numeric strings and symbols
- If an alphabet comes immediately after a number, then it converts it to uppercase
- The title() Function ignores numeric strings and symbols
- capitalize() Function
- Function Name
- capitalize()
- Syntax
string.capitalize()
- Purpose
- The main purpose of capitalize() function is to
- convert the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters
- The main purpose of capitalize() function is to
- Note
- The capitalize() Function ignores numeric strings and symbols
- upper() Function
- Function Name
- upper()
- Syntax
string.upper()
- Purpose
- The main purpose of upper() function is to
- convert all characters of a String in uppercase
- The main purpose of upper() function is to
- lower() Function
- Function Name
- lower()
- Syntax
string.lower()
- Purpose
- The main purpose of lower() function is to
- convert all characters of a String in lowercase
- The main purpose of lower() function is to
- center() Function
- Function Name
- center()
- Syntax
string.center(width, fillchar)
- Purpose
- The main purpose of center() function is to
- align a String to the center by filling paddings to left and right of the string
- The main purpose of center() function is to
- Example 1 – Formatting a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Format Strings using Built-in Functions
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to format string using following built-in Functions i.e., title(), capitalize(), upper(), lower() and center()
'''
# Input + Processing + Output
try:
# Initialize a Message
message = 'Allah is one.'
# Using title() Function
print('---Original String before using title() Function---')
print(message)
print("")
print('---New String after using title() Function---')
print(message.title())
# Using capitalize() Function
print("")
print('---Original String before using capitalize() Function---')
print(message)
print("")
print('---New String after using capitalize() Function---')
print(message.capitalize())
# Using upper() Function
print("")
print('---Original String before using upper() Function---')
print(message)
print("")
print('---New String after using upper() Function---')
print(message.upper())
# Using lower() Function
print("")
print('---Original String before using lower() Function---')
print(message)
print("")
print('---New String after using lower() Function---')
print(message.lower())
# Using center() Function
print("")
print('---Original String before using center() Function---')
print("Original Message: "+ message)
print("")
print('---New String after using center() Function---')
print(message.center(50))
except:
print('Error Occurred')
---Original String before using title() Function---
Allah is one.
---New String after using title() Function---
Allah Is One.
---Original String before using capitalize() Function---
Allah is one.
---New String after using capitalize() Function---
Allah is one.
---Original String before using upper() Function---
Allah is one.
---New String after using upper() Function---
ALLAH IS ONE.
---Original String before using lower() Function---
Allah is one.
---New String after using lower() Function---
allah is one.
---Original String before using center() Function---
Original Message: Allah is one.
---New String after using center() Function---
Allah is one.
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is the last Messenger of Allah. |
- Questions
- Apply following functions on String 1 and print the original and new string on the Output Screen?
- title()
- capitalize()
- upper()
- lower()
- center()
- Apply following functions on String 1 and print the original and new string on the Output Screen?
Your Turn Task 1
- Task
- Apply following functions on String 1 and print the original and new string on the Output Screen?
- title()
- capitalize()
- upper()
- lower()
- center()
- Apply following functions on String 1 and print the original and new string on the Output Screen?
Accessing Elements of a String
- Accessing Elements of a String
- In Sha Allah, in next Slides, I will access elements of String using following methods
- Method 1: Accessing Elements of a String using Indexing
- Method 2: Accessing Elements of a String using Slicing
- Method 3: Accessing Elements of a String using split() Function
- Method 1: Accessing Elements of a String using Indexing
- Indexing
- In python, Indexing is used to access individual element (i.e., a single character) of a String
- Syntax
string[index]
- Purpose
- The main purpose of indexing is to
- access a specific element (i.e., a single character) of a String
- Note
- In Python, Index
- Start value = 0
- End value = Length of String – 1
- In Indexing, we can also have negative offset
- In Python, Index
- The main purpose of indexing is to
- Indexing (S[i]) Fetches Elements of a String at Offsets
- The first element is at offset 0
- S[0] fetches the first element
- Negative indexes mean to count backward from the end or right
- S[−2] fetches the second item from the end (like S[len(S)−2])
- Method 2: Accessing Elements of a String using Slicing
- Slicing
- A Slice is a subset of elements extracted from a String
- Note
- A single slice will always comprise of contiguous elements
- Syntax
string[start_index : ending_index]
- Purpose
- The main purpose of slicing is to
- extract a portion from a String
- The main purpose of slicing is to
- Slicing (S[i:j]) Extracts Contiguous Elements of a String
- S[1:3] fetches elements at offsets 1 up to (but not including 3)
- S[1:] fetches elements at offset 1 through the end (the String length)
- S[:3] fetches items at offset 0 up to (but not including 3)
- S[:−1] fetches elements at offset 0 up to (but not including the last element)
- S[:] fetches elements at offsets 0 through the end (this effectively performs a top level copy of S)
- Method 3: Accessing Elements of a String using split() Function
- Function Name
- split()
- Syntax
string.split(separator, maxsplit)
- You can specify the separator
- Default separator is any whitespace
- Purpose
- The main purpose of split() function is to
- chop up a string into a list of substrings
- The main purpose of split() function is to
- Example 1 -Accessing Elements of a String using Indexing, Slicing and Split() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Access Elements of a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to access elements from a string using indexing, slicing and split() function
'''
# Input + Processing + Output
try:
# Initialize a Message
message = 'Allah is one. Allah is the creator of heavens and earth. Allah has control over everything.'
# Accessing Elements of a String using Indexing
print("")
print('---Original String before Indexing---')
print(message)
print("")
print('---New String after Indexing---')
# Access First Element of String
print("Access Element at First Index i.e., message[0] is: "+ message[0])
# Access 14th Element of String
print("Access Element at 14th Index i.e., message[14] is: "+ message[14])
# Access Last Element of String
print("Access Element at last Index i.e., message[-1] is: "+ message[-1])
# Using Slicing
print("")
print('---Original String before Slicing---')
print(message)
print("")
print('---New String after Slicing---')
# Access First Sentence of String with stop value only i.e., [:13]
print("Access First Sentence of String with stop value only i.e., [:13]: "+ message[:13])
# Access First Sentence of String with both start and stop value i.e., [0:13]
print("Access First Sentence of String with both start and stop value i.e., [0:13]: "+ message[0:13])
# Access Middle Sentence of String
print("Access Element from Middle Sentence i.e., message[14:53]: "+ message[14:53])
# Access Last Sentence of String with start value only i.e., message[55:]
print("Access Last Sentence of String with start value only i.e., message[55:]: "+ message[55:])
# Access Last Sentence of String with both start and stop value i.e., [55:91]
print("Access Element from Last Sentence i.e.,message[55:91]: "+ message[55:91])
# Split String on basis of full stop (.) using split() Function
print("")
print('---Original String before using split() Function---')
print(message)
print("")
print('---New String after using split() Function---')
print(message.split('.'))
# Split String on basis of spaces using split() Function
print("")
print('---Original String before using split() Function---')
print(message)
print("")
print('---New String after using split() Function---')
print(message.split(' '))
except:
print('Error Occurred')
---Original String before Indexing---
Allah is one. Allah is the creator of heavens and earth. Allah has control over everything.
---New String after Indexing---
Access Element at First Index i.e., message[0] is: A
Access Element at 14th Index i.e., message[14] is: A
Access Element at last Index i.e., message[-1] is: .
---Original String before Slicing---
Allah is one. Allah is the creator of heavens and earth. Allah has control over everything.
---New String after Slicing---
Access First Sentence of String with stop value only i.e., [:13]: Allah is one.
Access First Sentence of String with both start and stop value i.e., [0:13]: Allah is one.
Access Element from Middle Sentence i.e., message[14:53]: Allah is the creator of heavens and ear
Access Last Sentence of String with start value only i.e., message[55:]: . Allah has control over everything.
Access Element from Last Sentence i.e.,message[55:91]: . Allah has control over everything.
---Original String before using split() Function---
Allah is one. Allah is the creator of heavens and earth. Allah has control over everything.
---New String after using split() Function---
['Allah is one', ' Allah is the creator of heavens and earth', ' Allah has control over everything', '']
---Original String before using split() Function---
Allah is one. Allah is the creator of heavens and earth. Allah has control over everything.
---New String after using split() Function---
['Allah', 'is', 'one.', 'Allah', 'is', 'the', 'creator', 'of', 'heavens', 'and', 'earth.', 'Allah', 'has', 'control', 'over', 'everything.']
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is role model for us in all fields of life. |
- Questions
- Apply following techniques to access elements of a String (as shown in this Chapter) on String 1 and print the original and new string on the Output Screen?
- Indexing
- Slicing
- Splitting
- Apply following techniques to access elements of a String (as shown in this Chapter) on String 1 and print the original and new string on the Output Screen?
Your Turn Task 1
- Task
- Consider a String (similar to the one given in the TODO Task) and answer the questions given below.
- Questions
- Apply following techniques to access elements of a String (as shown in this Chapter) on selected String and print the original and new string on the Output Screen?
- Indexing
- Slicing
- Splitting
- Apply following techniques to access elements of a String (as shown in this Chapter) on selected String and print the original and new string on the Output Screen?
Removing Whitespaces from a String
- Removing Whitespaces from a String
- In Sha Allah, in next Slides, I will present following functions to remove white space from a String
- strip()
- rstrip()
- lstrip()
- strip() Function
- Function Name
- strip()
- Syntax
string. strip([characters])
- If the characters parameter is given, and if the given characters match, the characters at the start or end of the string will be removed from the original string, and the rest of the string will be returned
- Purpose
- The main purpose of strip() function is to
- remove whitespace from both the left and the right sides of the string at the same time
- Note
- In case the string does not have any whitespaces at the start or end, the string will be returned as it is and will match with the original string
- The main purpose of strip() function is to
- rstrip() Function
- Function Name
- rstrip()
- Syntax
string.rstrip()
- Purpose
- The main purpose of rstrip() function is to
- Removes whitespaces from the right side of a string
- The main purpose of rstrip() function is to
- lstrip() Function
- Function Name
- rstrip()
- Syntax
string.lstrip()
- Purpose
- The main purpose of rstrip() function is to
- Removes whitespaces from the right side of a string
- The main purpose of rstrip() function is to
- lstrip() Function
- Function Name
- lstrip()
- Syntax
string.lstrip()
- Purpose
- The main purpose of lstrip() function is to
- Remove whitespaces from the left side of a string
- The main purpose of lstrip() function is to
- Example 1 – Removing Whitespaces from a String using strip() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Remove Whitespaces from a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to remove Whitespaces from a String using strip() Function
'''
# Input + Processing + Output
try:
# Initialize a Message
message_1 = ' Allah is one.'
message_2 = ' Allah is the creator of heavens and earth.'
message_3 = 'Allah has control over everything. '
# Using strip() Function on message_1
print("")
print('---Original String before using strip() Function---')
print(message_1)
print("Length of Original String i.e., message_1: ",len(message_1))
print("")
print('---New String after using strip() Function---')
print(message_1.strip())
print("Length of New String i.e., message_1: ",len(message_1.strip()))
# Using strip() Function on message_2
print("")
print('---Original String before using strip() Function---')
print(message_2)
print("Length of Original String i.e., message_2: ",len(message_2))
print("")
print('---New String after using strip() Function---')
print(message_2.strip())
print("Length of New String i.e., message_2: ",len(message_2.strip()))
# Using strip() Function on message_3
print("")
print('---Original String before using strip() Function---')
print(message_3)
print("Length of Original String i.e., message_3 : ", len(message_3))
print("")
print('---New String after using strip() Function---')
print(message_3.strip())
print("Length of New String i.e., message_3: ",len(message_3.strip()))
except:
print('Error Occurred')
---Original String before using strip() Function---
Allah is one.
Length of Original String i.e., message_1: 18
---New String after using strip() Function---
Allah is one.
Length of New String i.e., message_1: 15
---Original String before using strip() Function---
Allah is the creator of heavens and earth.
Length of Original String i.e., message_2: 45
---New String after using strip() Function---
Allah is the creator of heavens and earth.
Length of New String i.e., message_2: 42
---Original String before using strip() Function---
Allah has control over everything.
Length of Original String i.e., message_3 : 37
---New String after using strip() Function---
Allah has control over everything.
Length of New String i.e., message_3: 34
- Example 2 – Removing Whitespaces from a String using rstrip() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Remove Whitespaces from a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to remove Whitespaces from a String using rstrip() Function
'''
# Input + Processing + Output
try:
# Initialize a Message
message_1 = ' Allah is one.'
message_2 = ' Allah is the creator of heavens and earth.'
message_3 = 'Allah has control over everything. '
# Using rstrip() Function on message_1
print("")
print('---Original String i.e., message_1 before using rstrip() Function---')
print(message_1)
print("Length of Original Message i.e., message_1: ",len(message_1))
print("")
print('---New String i.e., message_1 after using rstrip() Function---')
print(message_1.rstrip())
print("Length of New Message: ",len(message_1.rstrip()))
# Using rstrip() Function on message_2
print("")
print('---Original String i.e., message_2 before using rstrip() Function---')
print(message_2)
print("Length of Original Message i.e., message_2: ",len(message_2))
print("")
print('---New String i.e., message_2 after using rstrip() Function---')
print(message_2.rstrip())
print("Length of New Message i.e., message_2: ",len(message_2.rstrip()))
# Using rstrip() Function on message_3
print("")
print('---Original String i.e., message_3 before using rstrip() Function---')
print(message_3)
print("Length of Original Message i.e., message_3: ", len(message_3))
print("")
print('---New String i.e., message_3 after using rstrip() Function---')
print(message_3.rstrip())
print("Length of New Message i.e., message_3: ",len(message_3.rstrip()))
except:
print('Error Occurred')
---Original String i.e., message_1 before using rstrip() Function---
Allah is one.
Length of Original Message i.e., message_1: 18
---New String i.e., message_1 after using rstrip() Function---
Allah is one.
Length of New Message: 18
---Original String i.e., message_2 before using rstrip() Function---
Allah is the creator of heavens and earth.
Length of Original Message i.e., message_2: 45
---New String i.e., message_2 after using rstrip() Function---
Allah is the creator of heavens and earth.
Length of New Message i.e., message_2: 45
---Original String i.e., message_3 before using rstrip() Function---
Allah has control over everything.
Length of Original Message i.e., message_3: 37
---New String i.e., message_3 after using rstrip() Function---
Allah has control over everything.
Length of New Message i.e., message_3: 34
- Example 3 – Removing Whitespaces from a String using lstrip() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Remove Whitespaces from a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to remove Whitespaces from a String using lstrip() Function
'''
# Input + Processing + Output
try:
# Initialize a Message
message_1 = ' Allah is one.'
message_2 = ' Allah is the creator of heavens and earth.'
message_3 = 'Allah has control over everything. '
# Using lstrip() Function on message_1
print("")
print('---Original String i.e., message_1 before using lstrip() Function---')
print(message_1)
print("Length of Original Message i.e., message_1: ",len(message_1))
print("")
print('---New String i.e., message_1 after using lrip() Function---')
print(message_1.lstrip())
print("Length of New Message: ",len(message_1.lstrip()))
# Using lstrip() Function on message_2
print("")
print('---Original String i.e., message_2 before using lstrip() Function---')
print(message_2)
print("Length of Original Message i.e., message_2: ",len(message_2))
print("")
print('---New String i.e., message_2 after using lstrip() Function---')
print(message_2.lstrip())
print("Length of New Message i.e., message_2: ",len(message_2.lstrip()))
# Using lstrip() Function on message_3
print("")
print('---Original String i.e., message_3 before using lstrip() Function---')
print(message_3)
print("Length of Original Message i.e., message_3: ", len(message_3))
print("")
print('---New String i.e., message_3 after using lstrip() Function---')
print(message_3.lstrip())
print("Length of New Message i.e., message_3: ",len(message_3.lstrip()))
except:
print('Error Occurred')
---Original String i.e., message_1 before using lstrip() Function---
Allah is one.
Length of Original Message i.e., message_1: 18
---New String i.e., message_1 after using lrip() Function---
Allah is one.
Length of New Message: 15
---Original String i.e., message_2 before using lstrip() Function---
Allah is the creator of heavens and earth.
Length of Original Message i.e., message_2: 45
---New String i.e., message_2 after using lstrip() Function---
Allah is the creator of heavens and earth.
Length of New Message i.e., message_2: 42
---Original String i.e., message_3 before using lstrip() Function---
Allah has control over everything.
Length of Original Message i.e., message_3: 37
---New String i.e., message_3 after using lstrip() Function---
Allah has control over everything.
Length of New Message i.e., message_3: 37
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
“ Hazrat Muhammad (PBUH) is the last Messenger of Allah. “ |
- Questions
- Apply following functions on String 1 and print the original and new string on the Output Screen?
- strip()
- rstrip()
- lstrip()
- Apply following functions on String 1 and print the original and new string on the Output Screen?
Your Turn Task 1
- Task
- Consider a String (similar to the one given in the TODO Task) and answer the questions given below.
- Questions
- Apply following functions on String 1 and print the original and new string on the Output Screen?
- strip()
- rstrip()
- lstrip()
- Apply following functions on String 1 and print the original and new string on the Output Screen?
String Conversion
- String Conversion
- Function Name
- str()
- Syntax
str()
- Purpose
- The main purpose of str() function is to
- convert a given object (integer, float etc.) into a string
- The main purpose of str() function is to
- String Conversion
- Function Name
- int()
- Syntax
int()
- Purpose
- The main purpose of int() function is to
- convert a given object (string, float etc.) into an integer
- The main purpose of int() function is to
- Example 1 – String Conversion
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = String Conversion
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to convert a string from data type string to numbers and from numbers to string
'''
# Input + Processing + Output
try:
# Initialize Variable
number = 786
message = 'Allah is one.'
string_number = '786'
# Using str() Function
print('---Original Number before Conversion into String---')
print(number)
print('Data Type of Number before Converting into String:')
print(type(number))
print('---New Number after Conversion into String---')
print(str(number))
print('Data Type of Number after Converting into String')
print(type(str(number)))
print("")
# Using int() Function
print('---Original String before Conversion into Number---')
print(string_number)
print('Data Type of String before Converting into Number:')
print(type(string_number))
print('---New String after Conversion into Number---')
print(int(string_number))
print('Data Type of String after Converting into Number:')
print(type(int(string_number)))
print("")
# Using int() Function
print('---Original String before Conversion into Number---')
print(message)
print('Data Type of String before Converting into Number:')
print(type(message))
print('---New String after Conversion into Number---')
print(int(message))
print('Data Type of String after Converting into Number:')
print(type(int(message)))
except:
print('Error Occurred')
---Original Number before Conversion into String---
786
Data Type of Number before Converting into String:
---New Number after Conversion into String---
786
Data Type of Number after Converting into String
---Original String before Conversion into Number---
786
Data Type of String before Converting into Number:
---New String after Conversion into Number---
786
Data Type of String after Converting into Number:
---Original String before Conversion into Number---
Allah is one.
Data Type of String before Converting into Number:
---New String after Conversion into Number---
Error Occurred
TODO and Your Turn
TODO Task 1
- Task
- Consider the following data values and answer the questions given below
String 1 |
“125” |
Integer 1 |
428 |
- Questions
- Apply str() function on Integer 1 and print the original Integer and new String on the Output Screen?
- Apply int() function on String 1 and print the original String and new Integer on the Output Screen?
Your Turn Task 1
- Task
- Consider an Integer and String (similar to the ones given in the TODO Task) and answer the questions given below.
- Questions
- Apply str() function on Integer 1 and print the original Integer and new String on the Output Screen?
- Apply int() function on String 1 and print the original String and new Integer on the Output Screen?
Operations on Strings
Operation 1 – Creation
- Methods to Create a String
- I have already presented methods to create a String in the previous Section i.e.,
- Creating a String
Operation 2 – Insertion
- Methods to Insert a Character in a String
- In Sha Allah, in next Slides, I will present three methods to insert a character in a String
- Method 1: Insert Character at Start of a String
- Method 2: Insert Character at a Specific Position of a String
- Method 3: Insert Character at End of a String
- Operations and Functions to Insert Character(s) in a String
- In Sha Allah, I will use the following operator and functions to Insert Character(s) in a String
- Concatenation Operator (+)
- join() Function
- Formatting Operator (%)
- format() Function
- F-String Prefix
- find() Function
- Concatenation Operator (+)
- Operator Name
- +
- Syntax
string_1 + string_2
- Purpose
- The main purpose of Concatenation Operator (+) is to
- join two strings together
- The main purpose of Concatenation Operator (+) is to
- join() Function
- Function Name
- join()
- Syntax
string.join()
- Purpose
- The main purpose of join() function is to
- join two strings
- The main purpose of join() function is to
- Formatting Operator (%)
- Operator Name
- %
- Syntax
%s
- Purpose
- The main purpose of Formatting Operator (%) is to
- format a string
- The main purpose of Formatting Operator (%) is to
- format() Function
- Function Name
- format()
- Syntax
string.format(value 1, value 2...,value n)
- Purpose
- The main purpose of format() Function is to
- perform multiple substitutions and value formatting
- The main purpose of format() Function is to
- F-String Prefix
- Function Name
- F-String
- Syntax
f"{string}"
- Purpose
- The main purpose of F-string Prefix is to
- format a string
- Note
- F-string Prefix is faster than % formatting and format()
- The main purpose of F-string Prefix is to
- find() Function
- Function Name
- find()
- Syntax
string.find(value, start, end)
- Purpose
- The main purpose of find() Function is to
- find the first occurrence of the specified value in a String
- Note
- The find() method returns -1 if the value is not found
- The main purpose of find() Function is to
- Example 1 - Method 1: Insert Character at Start of a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Insert Character at Start of a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to insert character at start of a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = 'Allah is One.'
print('---Original String before using + Operator---')
print(message)
# Using + Operator to insert Element at First Index of a String
new_message = "*" + message[0:]
print('---New String after using + Operator ---')
print(new_message)
print("")
# Using join() Function to insert Element at First Index of a String
print('---Original String before using join() Function---')
print(message)
newmessage = ''.join(("*",message))
print('---New String after using join() Function---')
print(newmessage)
print("")
# Using % Operator to insert Element at First Index of a String
print('---Original String before using % Operator---')
print(message)
new_message = "%sAllah is One." %'*'
print('---New String after using % Operator---')
print(new_message)
print("")
# Using format() Function to insert Element at First Index of a String
print('---Original String before using format() Function---')
print(message)
new_message = "{}Allah is One.".format('*')
print('---New String after using format() Function---')
print(new_message)
print("")
# Using f Prefix to insert Element at First Index of a String
print('---Original String before using f Prefix---')
print(message)
new_message = f"{'*'}Allah is One."
print('---New String after using f Prefix---')
print(new_message)
print("")
# Using find() Function to insert Element at First Index of a String
print('---Original String before using find() Function---')
print(message)
index = message.find('Allah')
final_string = '*' + message[index:]
print('---New String after using find() Function---')
print(final_string)
print("")
'''Using split(), join() and insert() Functions to insert Element at First Index of a String '''
print('---Original String before using split() Function---')
print(message)
split_strings = message.split()
split_strings.insert(0, '*')
updated_string = ' '.join(split_strings)
print('---New String after using split() Function---')
print(updated_string)
except:
print('Error Occurred')
---Original String before using + Operator---
Allah is One.
---New String after using + Operator ---
*Allah is One.
---Original String before using join() Function---
Allah is One.
---New String after using join() Function---
*Allah is One.
---Original String before using % Operator---
Allah is One.
---New String after using % Operator---
*Allah is One.
---Original String before using format() Function---
Allah is One.
---New String after using format() Function---
*Allah is One.
---Original String before using f Prefix---
Allah is One.
---New String after using f Prefix---
*Allah is One.
---Original String before using find() Function---
Allah is One.
---New String after using find() Function---
*Allah is One.
---Original String before using split() Function---
Allah is One.
---New String after using split() Function---
* Allah is One.
- Example 2 - Method 2: Insert Character at a Specific Position of a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Insert Character at a Specific Position of a String programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to insert character at a specific position in a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = 'Allah is One.'
print('---Original String before using + Operator---')
print(message)
# Using + Operator to insert Element at Last Index of a String
new_message = message[:0] + "*"
print('---New String after using + Operator ---')
print(new_message)
print("")
# Using join() Function to insert Element at Last Index of a String
print('---Original String before using join() Function---')
print(message)
newmessage = ''.join((message,"*"))
print('---New String after using join() Function---')
print(newmessage)
print("")
# Using % Operator to insert Element at Last Index of a String
print('---Original String before using % Operator---')
print(message)
new_message = "Allah is One.%s" %'*'
print('---New String after using % Operator---')
print(new_message)
print("")
# Using format() Function to insert Element at Last Index of a String
print('---Original String before using format() Function---')
print(message)
new_message = "Allah is One.{}".format('*')
print('---New String after using format() Function---')
print(new_message)
print("")
# Using f Prefix to insert Element at Last Index of a String
print('---Original String before using f Prefix---')
print(message)
new_message = f"Allah is One.{'*'}"
print('---New String after using f Prefix---')
print(new_message)
print("")
# Using find() Function to insert Element at Last Index of a String
print('---Original String before using find() Function---')
print(message)
index = message.find('.')
final_string = message[:index+1] + '*'
print('---New String after using find() Function---')
print(final_string)
print("")
'''Using split(), join() and insert() Functions to insert Element at Last Index of a String '''
print('---Original String before using split() Function---')
print(message)
split_strings = message.split()
split_strings.insert((len(message) + 1), '*')
updated_string = ' '.join(split_strings)
print('---New String after using split() Function---')
print(updated_string)
except:
print('Error Occurred')
---Original String before using + Operator---
Allah is One.
---New String after using + Operator ---
*
---Original String before using join() Function---
Allah is One.
---New String after using join() Function---
Allah is One.*
---Original String before using % Operator---
Allah is One.
---New String after using % Operator---
Allah is One.*
---Original String before using format() Function---
Allah is One.
---New String after using format() Function---
Allah is One.*
---Original String before using f Prefix---
Allah is One.
---New String after using f Prefix---
Allah is One.*
---Original String before using find() Function---
Allah is One.
---New String after using find() Function---
Allah is One.*
---Original String before using split() Function---
Allah is One.
---New String after using split() Function---
Allah is One. *
- Example 3 - Method 3: Insert Character at End of a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Insert Character at End of a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to insert character at end of a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = 'Allah is One.'
print('---Original String before using + Operator---')
print(message)
# Using + Operator to insert Element at Last Index of a String
new_message = message[:0] + "*"
print('---New String after using + Operator---')
print(new_message)
print("")
# Using join() Function to insert Element at Last Index of a String
print('---Original String before using join() Function---')
print(message)
newmessage = ''.join((message,"*"))
print('---New String after using join() Function---')
print(new_message)
print("")
# Using % Operator to insert Element at Last Index of a String
print('---Original String before using % Operator---')
print(message)
new_message = "Allah is One.%s" %'*'
print('---New String after using % Operator---')
print(new_message)
print("")
# Using format() Function to insert Element at Last Index of a String
print('---Original String before using format() Function---')
print(message)
new_message = "Allah is One.{}".format('*')
print('---New String after using format() Function---')
print(new_message)
print("")
# Using f Prefix to insert Element at Last Index of a String
print('---Original String before using f Prefix---')
print(message)
new_message = f"Allah is One.{'*'}"
print('---New String after using f Prefix---')
print(new_message)
print("")
# Using find() Function to insert Element at Last Index of a String
print('---Original String before using find() Function---')
print(message)
index = message.find('.')
final_string = message[:index+1] + '*'
print('---New String after using find() Function---')
print(final_string)
print("")
'''Using split(), join() and insert() Functions to insert Element at Last Index of a String '''
print('---Original String before using split() Function---')
print(message)
split_strings = message.split()
split_strings.insert((len(message) + 1), '*')
updated_string = ' '.join(split_strings)
print('---New String after using split() Function---')
print(updated_string)
except:
print('Error Occurred')
---Original String before using + Operator---
Allah is One.
---New String after using + Operator---
*
---Original String before using join() Function---
Allah is One.
---New String after using join() Function---
*
---Original String before using % Operator---
Allah is One.
---New String after using % Operator---
Allah is One.*
---Original String before using format() Function---
Allah is One.
---New String after using format() Function---
Allah is One.*
---Original String before using f Prefix---
Allah is One.
---New String after using f Prefix---
Allah is One.*
---Original String before using find() Function---
Allah is One.
---New String after using find() Function---
Allah is One.*
---Original String before using split() Function---
Allah is One.
---New String after using split() Function---
Allah is One. *
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is role model for us in all fields of life. |
- Questions
- Apply following operators and functions to insert characters at: (1) start, (2) specific position, and (3) end of String 1 (as shown in this Chapter) and print the original and new string on the Output Screen?
- Concatenation Operator (+)
- join() Function
- Formatting Operator (%)
- format() Function
- F-String Prefix
- find() Function
- Apply following operators and functions to insert characters at: (1) start, (2) specific position, and (3) end of String 1 (as shown in this Chapter) and print the original and new string on the Output Screen?
Your Turn Task 1
- Task
- Consider a String (similar to the one given in the TODO Task) and answer the questions given below.
- Questions
- Apply following operators and functions to insert characters at: (1) start, (2) specific position, and (3) end of String 1 (as shown in this Chapter) and print the original and new string on the Output Screen?
- Concatenation Operator (+)
- join() Function
- Formatting Operator (%)
- format() Function
- F-String Prefix
- find() Function
- Apply following operators and functions to insert characters at: (1) start, (2) specific position, and (3) end of String 1 (as shown in this Chapter) and print the original and new string on the Output Screen?
Operation 3 – Traverse
- Methods to Traverse a String
- In Sha Allah, in next Slides, I will present two methods to traverse a String
- Method 1: Traversing an Entire String
- Method 2: Traversing a String (Element by Element)
- Example 1 - Method 1: Traversing an Entire String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Traversing an Entire String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to traverse an entire string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = 'Allah'
# Traverse an entire String
print(message)
except:
print('Error Occurred')
Allah
- Example 2 - Method 2: Traversing a String (Element by Element)
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Traversing a String (Element by Element)
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to traverse a string (element by element) and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# ---Approach I - Iterate over a string (element by element) using for loop---
# Initialize Variable
message_1 = 'Allah is One.'
# Iterate over a string (element by element) using for loop
print(" ---Approach I - Iterate over a string (element by element) using for loop---")
print("---Traverse a String (Element by Element) using for Loop---")
for character in message_1:
print(character)
# ---Approach II - Iterate over a string (element by element) using Indexing---
# Initialize Variable
message_2 = 'Allah is One.'
# Iterate over a string (element by element) using for loop with Indexing
print(" ---Approach II - Iterate over a string (element by element) using Indexing---")
print("---Traverse a String (Element by Element) using for Loop with Indexing---")
for element in range(0, len(message_2)):
print("message_2[",element,"]: " + message_2[element])
# ---Approach III - Iterate over a string (element by element) using Slicing---
# Initialize Variable
message_3 = 'Allah is One.'
counter = 0
print("---Approach III - Iterate over a string (element by element) using Slicing---")
# Iterate over a string (element by element) using for loop with Slicing
print("---Traverse a String (Element by Element) using for Loop with Slicing---")
# Slicing Operator => string[starting index : ending index : step value]
for element in message_3[0 : len(message_3): 1]:
counter = counter + 1
print("message_3[",counter,"]: " + element)
except:
print('Error Occurred')
---Traverse a String (Element by Element) using for Loop---
A
l
l
a
h
i
s
O
n
e
.
---Approach II - Iterate over a string (element by element) using Indexing---
---Traverse a String (Element by Element) using for Loop with Indexing---
message_2[ 0 ]: A
message_2[ 1 ]: l
message_2[ 2 ]: l
message_2[ 3 ]: a
message_2[ 4 ]: h
message_2[ 5 ]:
message_2[ 6 ]: i
message_2[ 7 ]: s
message_2[ 8 ]:
message_2[ 9 ]: O
message_2[ 10 ]: n
message_2[ 11 ]: e
message_2[ 12 ]: .
---Approach III - Iterate over a string (element by element) using Slicing---
---Traverse a String (Element by Element) using for Loop with Slicing---
message_3[ 1 ]: A
message_3[ 2 ]: l
message_3[ 3 ]: l
message_3[ 4 ]: a
message_3[ 5 ]: h
message_3[ 6 ]:
message_3[ 7 ]: i
message_3[ 8 ]: s
message_3[ 9 ]:
message_3[ 10 ]: O
message_3[ 11 ]: n
message_3[ 12 ]: e
message_3[ 13 ]: .
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Muhammad |
- Questions
- Traverse String 1 using the methods presented in this Chapter?
Your Turn Task 1
- Task
- Consider a String (similar to the one given in the TODO Task) and answer the questions given below.
- Questions
- Traverse the selected String using the methods presented in this Chapter?
Operation 4 – Searching
- Methods to Search Character from a String
- In Sha Allah, in next Slides, I will present two methods to search a String
- Method 1: Search Specific Character from a String
- Example 1 - Method 1: Search Specific Character from a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Search Specific Character from a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to search specific character from a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = 'Allah is one. He is the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim. '
print('---Original String before using find() Function---')
print(message)
# Using find() Function to Search a Word from a String
index_of_character = message.find('creator')
print('---Index of Searched Term (creator) returned by Search Function---')
print(index_of_character)
print("")
# Using find() Function to Search a Character from a String
print('---Original String before using find() Function---')
print(message)
index_of_character = message.find('a')
print('Searching all instances of a Search Term (a)')
print(index_of_character)
print("")
# Using split() and find() Function to Search a String using for Loop
split_message = message.split()
for elem in split_message:
index = elem.find("Allah")
if index != -1:
print(elem)
except:
print('Error Occurred')
---Original String before using find() Function---
Allah is one. He is the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim.
---Index of Searched Term (creator) returned by Search Function---
24
---Original String before using find() Function---
Allah is one. He is the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim.
Searching all instances of a Search Term (a)
3
Allah
Allah.
Allah
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is role model for us in all fields of life. |
- Questions
- Apply methods presented in this Chapter to search the following elements in String 1
- z
- PBUH
- Apply methods presented in this Chapter to search the following elements in String 1
Your Turn Task 1
- Task
- Consider a String (similar to the one given in the TODO Task) and answer the questions given below.
- Questions
- Apply methods presented in this Chapter to search the following elements in String 1
Operation 5 – Sorting
- Methods to Sort Character from a String
- In Sha Allah, in next Slides, I will present two methods of sorting a String
- Method 1: Sort the String in Ascending Order
- Method 2: Sort the String in Descending Order
- Method 3: Sort the String Alphabetically
- sorted() Function
- Function Name
- sorted()
- Syntax
sorted(iterable, key=key, reverse=reverse)
- Purpose
- The main purpose of sorted() function is to
- Alphabetically sort a String
- The main purpose of sorted() function is to
- Example 1 - Method 1: Sort the String in Ascending Order
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Sort the String in Ascending Order
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to sort the string in ascending order and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Approach I - sorted() Function to arrange string in Ascending Order
# Initialize Variable
message = 'Day of Judgement'
print('---Approach I - sorted() Function to arrange string in Ascending Order---')
print('---Original String before using sorted() Function---')
print(message)
# Using sorted() Function to arrange string in Ascending Order
messages = sorted(message, reverse=True)
print('---New String after using sorted() Function---')
print(messages)
print('')
# Approach II – sorted() and split() Function to arrange string in Ascending Order
print('---Approach II - sorted() and split() Function to arrange string in Ascending Order---')
# Using sorted() and split() Function to arrange string in Ascending Order
messages = sorted(message.split(' '),reverse = True)
print('---New String after using sorted() Function---')
print(messages)
except:
print('Error Occurred')
---Approach I - sorted() Function to arrange string in Ascending Order---
---Original String before using sorted() Function---
Day of Judgement
---New String after using sorted() Function---
['y', 'u', 't', 'o', 'n', 'm', 'g', 'f', 'e', 'e', 'd', 'a', 'J', 'D', ' ', ' ']
---Approach II - sorted() and split() Function to arrange string in Ascending Order---
---New String after using sorted() Function---
['of', 'Judgement', 'Day']
- Example 2 - Method 2: Sort the String in Descending Order
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Sort the String in Descending Order
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to sort the string in descending order and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Approach I - sorted() Function to arrange string in Descending Order
# Initialize Variable
message = 'Day of Judgement'
print('---Approach I - sorted() Function to arrange string in Descending Order---')
print('---Original String before using sorted() Function---')
print(message)
# Using sorted() Function to arrange string in Descending Order
messages = sorted(message, reverse=False)
print('---New String after using sorted() Function---')
print(messages)
print('')
# Approach II – sorted() and split() Function to arrange string in Descending Order
print('---Approach II - sorted() and split() Function to arrange string in Descending Order---')
# Using sorted() and split() Function to arrange string in Descending Order
messages = sorted(message.split(' '),reverse = False)
print('---New String after using sorted() Function---')
print(messages)
except:
print('Error Occurred')
---Approach I - sorted() Function to arrange string in Descending Order---
---Original String before using sorted() Function---
Day of Judgement
---New String after using sorted() Function---
[' ', ' ', 'D', 'J', 'a', 'd', 'e', 'e', 'f', 'g', 'm', 'n', 'o', 't', 'u', 'y']
---Approach II - sorted() and split() Function to arrange string in Descending Order---
---New String after using sorted() Function---
['Day', 'Judgement', 'of']
- Example 3 - Method 3: Sort the String Alphabetically
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Sort the String Alphabetically
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to sort the string in alphabetically and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = 'Allah is One.'
print('---Original String before using sorted() Function---')
print(message)
# Using join() and sorted() Function to sort the String Alphabetically
message = ' '.join(sorted(message))
print('---New String after using sorted() Function---')
print(message)
except:
print('Error Occurred')
---Original String before using sorted() Function---
Allah is One.
---New String after using sorted() Function---
. A O a e h i l l n s
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is role model for us in all fields of life. |
- Questions
- Apply method presented in this Chapter to sort String 1
Your Turn Task 1
- Task
- Consider a String (similar to the one given in the TODO Task) and answer the questions given below.
- Questions
- Apply methods presented in this Chapter to sort the selected String?
Operation 6 – Merging
- Methods to Merge Character from a String
- In Sha Allah, in next Slides, I will present two methods to merge / concatenate a String
- Method 1: Concatenate a String using + Operator
- Method 2: Merge a String using join() Function
- Example 1 - Method 1: Concatenate a String using + Operator
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Concatenate a String using + Operator
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to concatenate a string using + operator and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message_1 = 'Allah is One.'
message_2 = 'The Master of Day of Judgement'
print('---Original Message i.e., message_1---')
print(message_1)
print('---Original Message i.e., message_2---')
print(message_2)
# Using + Operator Concatenate Two Strings
join_message = message_1 + message_2
print('---New String after using + Operator---')
print(join_message)
except:
print('Error Occurred')
---Original Message i.e., message_1---
Allah is One.
---Original Message i.e., message_2---
The Master of Day of Judgement
---New String after using + Operator---
Allah is One.The Master of Day of Judgement
- Example 2 - Method 2: Merge a String using join() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Merge a String using join() Function
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to merge a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message_1 = 'Allah is One.'
message_2 = 'The Master of Day of Judgement'
print('---Original Message i.e., message_1---')
print(message_1)
print('---Original Message i.e., message_2 ---')
print(message_2)
# Using join() Function to Concatenate Two Strings
join_message = ' '.join([message_1,message_2])
print('---New String after using join() Function---')
print(join_message)
except:
print('Error Occurred')
---Original Message i.e., message_1---
Allah is One.
---Original Message i.e., message_2 ---
The Master of Day of Judgement
---New String after using join() Function---
Allah is One. The Master of Day of Judgement
Operation 7 – Updation
- Methods to Update Character from a String
- In Sha Allah, in next Slides, I will present methods to update a String
- Method 1: Update Character of String using replace() Function
- Method 2: Update Words of String using replace() Function
- replace() Function
- Function Name
- replace()
- Syntax
string.replace(oldvalue, newvalue, count)
- Purpose
- The main purpose of replace() function is to
- replace a specified phrase with another specified phrase in a String
- Note
- By default, all occurrences of the specified phrase will be replaced
- The main purpose of replace() function is to
- Example 1 - Method 1: Update Words of String using replace() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Update Words of String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to update words of string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = "Allah is one. He's the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim."
print('---Original String before using replace() Function---')
print(message)
# Using replace() Function to Replace Words in a String
message = message.replace('Allah','God')
message = message.replace('Hazrat Muhammad (PBUH)', 'Huzoor S.A.W.W.')
message = message.replace('Messenger', 'Prophet')
print('---New String after using replace() Function---')
print(message)
except:
print('Error Occurred')
---Original String before using replace() Function---
Allah is one. He's the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim.
---New String after using replace() Function---
God is one. He's the creator of heavens and earth. He has control over everything. Huzoor S.A.W.W. is the last Prophet of God. One who does not accept Huzoor S.A.W.W. as last Prophet of God is a non-Muslim.
- Example 2 – Method 2 - Update Character of String using replace() Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Update Characters of String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to update characters of a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = "Allah is one. He's the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim."
print('---Original String before using replace() Function---')
print(message)
# Using replace() Function to Replace Character in a String
message = message.replace('o','O')
print('---New String after using replace() Function---')
print(message)
except:
print("Error Occurred")
---Original String before using replace() Function---
Allah is one. He's the creator of heavens and earth. He has control over everything. Hazrat Muhammad (PBUH) is the last Messenger of Allah. One who does not accept Hazrat Muhammad (PBUH) as last Messenger of Allah is a non-Muslim.
---New String after using replace() Function---
Allah is One. He's the creatOr Of heavens and earth. He has cOntrOl Over everything. Hazrat Muhammad (PBUH) is the last Messenger Of Allah. One whO dOes nOt accept Hazrat Muhammad (PBUH) as last Messenger Of Allah is a nOn-Muslim.
TODO and Your Turn
TODO Task 1
- Task
- Consider the following String and answer the questions given below
String 1 |
Hazrat Muhammad (PBUH) is role model |
String 2 |
for us in all fields of life. |
- Questions
- Apply method presented in this Chapter to merge String 1 and String 2
Your Turn Task 1
- Task
- Consider two Strings (similar to the ones given in the TODO Task) and answer the questions given below.
- Questions
- Apply methods presented in this Chapter to merge the two selected Strings?
Operation 8 – Deletion
- Methods to Search Character from a String
- In Sha Allah, in next Slides, I will present two methods to delete a String
- Method 1: Remove First Character from a String
- Method 2: Remove Character from Specific Location of a String
- Method 3: Remove Last Character from a String
- Example 1 - Method 1: Remove First Character from a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Remove First Character from a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to remove first character from a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = "*Allah is One."
print('---Original String before Removing first Character from String---')
print(message)
# Using Slicing to remove first character from a string
message = message[1:]
print('---New String after Removing first Character from String---')
print(message)
except:
print("Error Occurred")
---Original String before Removing first Character from String---
*Allah is One.
---New String after Removing first Character from String---
Allah is One.
- Example 2 - Method 2: Remove Character from Specific Location of a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Remove Character from Specific Location of a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to remove character from specific location of a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Approach I - Using replace() Function to Remove Character from a String
# Initialize Variable
message = " Day of Judgment"
print('Approach I - replace() Function to Remove Character from a String')
print('---Original String before Removing Character from String---')
print(message)
# Using replace() Function to Remove Character from a String
message = message.replace('o','')
print('---New String after Removing Character from String---')
print(message)
print('')
# Approach II – Use Slicing to Remove Character from a String
print(' Approach II – Use Slicing to Remove Characters from a String')
print('---Original String before Removing Character from String---')
print(message)
# Removing Character at index 3
# Using Slicing and Concatenation
del_char = message[:2] + message[3:]
print('---New String after Removing Character from String---')
print(del_char)
print('')
# Approach III – Using replace() Function to Remove Character from a String
print(' Approach III – Using replace() Function to Remove Characters from a String')
print('---Original String before Removing Character from String---')
print(message)
# Iterate over the String using for Loop
for character in message:
# Using replace() Function to Remove Character from a String
message = message.replace(" ", "")
print('---New String after Removing Character from String---')
print(message)
except:
print("Error Occurred")
Approach I - replace() Function to Remove Character from a String
---Original String before Removing Character from String---
Day of Judgment
---New String after Removing Character from String---
Day f Judgment
Approach II – Use Slicing to Remove Characters from a String
---Original String before Removing Character from String---
Day f Judgment
---New String after Removing Character from String---
Dy f Judgment
Approach III – Using replace() Function to Remove Characters from a String
---Original String before Removing Character from String---
Day f Judgment
---New String after Removing Character from String---
DayfJudgment
- Example 3 - Method 3: Remove Last Character from a String
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Remove Last Character from a String
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to remove last character from a string and display the result on the Output Screen
'''
# Input + Processing + Output
try:
# Initialize Variable
message = "Allah is One."
print('---Original String before Removing Last Character from a String---')
print(message)
# Using Slicing to remove last character from a string
message = message[:-1]
print('---New String after Removing Last Character from a String---')
print(message)
except:
print("Error Occurred")
---Original String before Removing Last Character from a String---
Allah is One.
---New String after Removing Last Character from a String---
Allah is One
Passing Strings to a Function
- Passing Strings to a Function
- In Sha Allah, in the next Slides, I will show how to pass string, integer and float Data Values to a Function
- Example 1 - Passing Strings to a Function
'''
Author and System Information
author_name = Ms. Samavi Salman
program_name = Passing Strings to a Function
programming_language = Python
operating_system = Windows 10
ide = Jupyter Notebook
licence = public_domain_1.0
start_date = 21-Jun-2022
end_data = 21-Jun-2022
'''
'''
Purpose of Program
The main purpose of the program is to pass strings to a function and display the result on the Output Screen
'''
def displayStudentInformation(name, age, cgpa, gender, qualification):
print("Name: ", name)
print("Age: ",age)
print("CGPA: ",cgpa)
print("Gender: ",gender)
print("Qualification: ",qualification)
if __name__ == "__main__": # main() Function
try:
# Input
name = input("Enter your Name")
age = int(input("Enter Age: "))
cgpa = float(input("Enter your CGPA"))
gender = input("Enter your Gender")
qualification = input("Enter your Qualification")
# Processing + Output
displayStudentInformation(name, age, cgpa, gender, qualification)
except ValueError:
print("Error! Enter Valid Values")
Name: Samavi
Age: 23
CGPA: 3.51
Gender: Female
Qualification: BS(SE)
TODO and Your Turn
TODO Task 1
- Task
- Consider the following Data Values and answer the questions given below
Data Values |
String: CNIC No. String: Address String: Country |
- Questions
- Take Input from User his / her CNIC No, Address and Country. Pass these three attributes to a Function and print the values on the Output Screen.
Your Turn Task 1
- Task
- Consider three attributes (similar to the ones given in the TODO Task) and answer the questions given below.
- Questions
- Take Input from Student his / her Reg. Number, Name and Degree Program. Pass these three attributes to a Function and print the values on the Output Screen
Chapter Summary
- Chapter Summary
In this Chapter, I presented the following main concepts:
- String
- A string is defined as a sequence of characters
- String Methods
- String Methods are special functions used to manipulate strings
- String Literals
- In Python, String Literals are surrounded by either single quotes, or double quotes, or triple quotes
- Single Quote, Double Quote and Triple Quote
- Single Quote
- In Python, Single Quotes are generally used for String Literals and Regular Expressions
- Double Quote
- In Python, Double Quotes are generally used for string representation
- Triple Quote
- In Python, Triple Quotes are generally used to allow strings to span multiple lines (which may include tabs, newlines, or any other special characters)
- Escape Sequences
- An Escape Sequence is defined using a combination of Two Characters, were
- First Character is a Backslash \ and
- Second Character is a Letter
- Creating a String
- In Python, generally a String is created using double quotes
- title()
- capitalize()
- upper()
- lower()
- center()
- Accessing Elements of a String
- Method 1: Accessing Elements of a String using Indexing
- Method 2: Accessing Elements of a String using Slicing
- Method 3: Accessing Elements of a String using split() Function
- Removing Whitespaces from a String
- strip()
- rstrip()
- lstrip()
- Operations on Strings
- Operation 1 – Creation
- Operation 2 – Insertion
- Operation 3 – Traversal
- Operation 4 – Searching
- in
- fine()
- startswith()
- endswith()
- Operation 5 – Sorting
- sorted()
- Operation 6 – Merging
- Using + operator
- Using join() Method
- Using format() Method
- Operation 7 – Updation
- replace()
- Operation 8 – Deletion
- del()
- In Python, generally a String is created using double quotes
- An Escape Sequence is defined using a combination of Two Characters, were
- Single Quote
In Next Chapter
- In Next Chapter
- In Sha Allah, in the next Chapter, I will present a detailed discussion on
- Lists in Python