[CH-6] String Manipulation
[CH-6] String Manipulation
Syllabus:-
Real-World Examples:
1. Extracting Substrings:
o Scenario: You're working with a customer database and need to extract the
first and last names from full names.
o Code:
Python
2. Reversing Strings:
o Scenario: You need to reverse the order of characters in a string for a
password encryption algorithm.
o Code:
Python
string = "hello"
reversed_string = string[::-1]
3. Creating Sublists:
o Scenario: You're analyzing a list of sales data and want to extract specific
time periods.
o Code:
Python
4. Filtering Elements:
o Scenario: You're working with a list of email addresses and need to extract
only those ending with ".com".
o Code:
Python
Additional Considerations:
Negative indices: These refer to elements from the end of the sequence. For example,
[-1] refers to the last element.
Omitting indices: If you omit the start index, it defaults to 0. If you omit the stop
index, it defaults to the length of the sequence. If you omit the step, it defaults to 1.
In Conclusion:
Slicing is a fundamental tool in Python programming that offers a concise and efficient way
to manipulate lists and strings. By understanding the syntax and its applications, you can
write more effective and readable code, especially when dealing with textual data or
structured information.
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks, or
triple quotation.
Example:
print("Hello")
print('Hello')
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
print(a)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
OUTPUT:-
Traversing a string
o Traversing a string in Python means accessing each character in the string
one by one. Here are a couple of ways to do it:
1. Using a for loop:
For loop: The for loop iterates over each character in the string automatically.
my_string = "Hello, World!"
OUTPUT:
H
e
l
l
o
,
W
o
r
l
d
!
2.While loop:-
my_string = "Hello, World!"
index = 0
while index < len(my_string):
print(my_string[index])
index += 1
While loop: The while loop uses an index to access each character in the string. The loop
continues as long as the index is less than the length of the string
Reversed a string:-
1.Method using for loop:
string="python"
length=len(string)
for a in range(-1,(-length-1),-1):
print(string[a])
OUTPUT:-
CODE Explanation
Initialization:
string = "python": This line creates a string object named string and assigns it
the value "python".
length = len(string): This line calculates the length of the string object and
stores it in the variable length. In this case, length will be 6.
Loop Iteration:
for a in range(-1, (-length-1), -1):: This line sets up a for loop that iterates
over a range of values.
o -1: This is the starting value for the loop variable a. It will initially be set to -
1.
o (-length-1): This expression calculates the ending value for the loop. Since
length is 6, the expression evaluates to -7.
o -1: This is the step value, indicating that the loop variable a will decrement by
1 in each iteration.
Printing Characters:
print(string[a]): This line prints the character at index a of the string object.
INPUT
string="python"
for i in reversed(string):
print(i,end=" ")
OUTPUT:
nohtyp
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
b = "Hello, World!"
print(b[-5:-2])
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
The upper() method returns the string in upper case:
INPUT
a = "Hello, World!"
print(a.upper())
OUTPUT:
HELLO, WORLD!
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of
the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
OUTPUT:
HelloWorld
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
F-Strings
F-String was introduced in Python 3.6, and is now the preferred way of
formatting strings.
Example
Create an f-string:
age = 36
txt = f" My name is John, I am {age}"
print(txt)
ESCAPE Character :-
INPUT:-
txt = "Code is like "humor" When you have to explain it, it’s bad."
print(txt)
ERROR….
OUTPUT:-
Example
The escape character allows you to use double quotes when you normally
would not be allowed:
Input:-
txt = "Hello\nWorld!"
print(txt)
Output:-
Hello
World!
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original string.
1) Python
String capitalize() Method:-
The capitalize() method returns a string where the first character is
upper case, and the rest is lower case.
Syntax
string.capitalize()
Example
The first character is converted to upper case, and the rest are converted to
lower case:
x = txt.capitalize()
print (x)
OUTPUT:-
Example
See what happens if the first character is a number:
x = txt.capitalize()
print (x)
If the word contains a number or a symbol, the first letter after that will be
converted to upper case.
Syntax
string.title()
Example
Make the first letter in each word upper case:
x = txt.title()
print(x)
OUTPUT:-
Welcome To My World
Exercise:-
txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x)
The index() method is almost the same as the find() method, the only
difference is that the find() method returns -1 if the value is not found. (See
example below)
Syntax
string.index(value, start, end)
Example
Where in the text is the first occurrence of the letter "e"?:
x = txt.index("e")
print(x)
Example
Where in the text is the first occurrence of the letter "e" when you only
search between position 5 and 10?:
x = txt.index("e", 5, 10)
print(x)
Example
If the value is not found, the find() method returns -1, but the index()
method will raise an exception:
print(txt.find("q"))
print(txt.index("q"))
OUTPUT:-
-1
Traceback (most recent call last):
File "demo_ref_string_find_vs_index.py", line 4 in <module>
print(txt.index("q"))
ValueError: substring not found
The find() method is almost the same as the index() method, the only
difference is that the index() method raises an exception if the value is not
found. (See example below)
Syntax
string.find(value, start, end)
Example
Where in the text is the word "welcome"?:
x = txt.find("welcome")
print(x)
OUTPUT:-
7
Python String count() Method
The count() method returns the number of times a specified value appears
in the string.
Syntax
string.count(value, start, end)
EXAMPLE:-
Return the number of times the value "apple" appears in the string:
x = txt.count("apple")
print(x)
Example
Search from position 10 to 24:
print(x)
Python
String endswith() Method
The endswith() method returns True if the string ends with the specified
value, otherwise False.
Syntax
string.endswith(value, start, end)
Example
Check if the string ends with a punctuation sign (.):
x = txt.endswith(".")
print(x)
Exercise
Check if position 5 to 11 ends with the phrase "my world.":
print(x)
Python
String startswith() Method
The startswith() method returns True if the string starts with the specified
value, otherwise False.
Syntax
string.startswith(value, start, end)
Example
Check if the string starts with "Hello":
x = txt.startswith("Hello")
print(x)
Exercise:-
Check if position 7 to 20 starts with the characters "wel":
x = txt.startswith("wel", 7, 20)
print(x)
Python
String isalpha() Method
The isalpha() method returns True if all the characters are alphabet letters
(a-z).
Syntax
string.isalpha()
Example
Check if all the characters in the text are letters:
txt = "CompanyX"
x = txt.isalpha()
print(x)
Exercise
Check if all the characters in the text is alphabetic:
txt = "Company10"
x = txt.isalpha()
print(x)
Python
String isalnum() Method
The isalnum() method returns True if all the characters are alphanumeric,
meaning alphabet letter (a-z) and numbers (0-9).
Syntax
string.isalnum()
Example
Check if all the characters in the text are alphanumeric:
txt = "Company12"
x = txt.isalnum()
print(x)
EXERCISE:--
x = txt.isalnum()
print(x)
Python
String isdigit() Method
The isdigit() method returns True if all the characters are digits, otherwise
False.
Syntax
string.isdigit()
Example
Check if all the characters in the text are digits:
txt = "50800"
x = txt.isdigit()
print(x)
Exercise:---
Check if all the characters in the text are digits:
print(a.isdigit())
print(b.isdigit())
Python
String islower() Method
The islower() method returns True if all the characters are in lower case,
otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax
string.islower()
Example
Check if all the characters in the text are in lower case:
x = txt.islower()
print(x)
OUTPUT:-
True
Exercise:----
Check if all the characters in the texts are in lower case:
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"
print(a.islower())
print(b.islower())
print(c.islower())
Python
String isspace() Method
The isspace() method returns True if all the characters in a string are
whitespaces, otherwise False.
Syntax
string.isspace()
Example
Check if all the characters in the text are whitespaces:
x = txt.isspace()
print(x)
OUTPUT:-
True
Exercise:---
Check if all the characters in the text are whitespaces:
x = txt.isspace()
print(x)
Python
String isupper() Method:
The isupper() method returns True if all the characters are in upper case,
otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax
string.isupper()
Example
Check if all the characters in the text are in upper case:
x = txt.isupper()
print(x)
Example
Check if all the characters in the texts are in upper case:
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"
print(a.isupper())
print(b.isupper())
print(c.isupper())
Syntax
string.lstrip(characters)
Example
Remove spaces to the left of the string:
x = txt.lstrip()
OUTPUT:-
of all fruits banana is my favorite
Exercise:-
Remove the leading characters:
txt = ",,,,,ssaaww.....banana"
x = txt.lstrip(",.asw")
print(x)
Syntax
string.rstrip(characters)
EXAMPLE:-
x = txt.rstrip()
OUTPUT:-
Exercise:---
Remove the trailing characters if they are commas, periods, s, q, or w:
txt = "banana,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x)
Leading means at the beginning of the string, trailing means at the end.
You can specify which character(s) to remove, if not, any whitespaces will be
removed.
Syntax
string.strip(characters)
Example
Remove spaces at the beginning and at the end of the string:
x = txt.strip()
Exercise:
Remove the leading and trailing characters:
txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt")
print(x)
Syntax
string.join(iterable)
Example
Join all items in a tuple into a string, using a hash character as separator:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
OUTPUT:--
John#Peter#Vicky
Exercise:--
Join all items in a dictionary into a string, using the word "TEST" as
separator:
x = mySeparator.join(myDict)
print(x)
Note: When using a dictionary as an iterable, the returned values are the
keys, not the values.
Note: When maxsplit is specified, the list will contain the specified number of
elements plus one.
Syntax
string.split(separator, maxsplit)
Example
Split a string into a list where each word is a list item:
x = txt.split()
print(x)
OUTPUT:--
['welcome', 'to', 'the', 'jungle']
Example
Use a hash character as a separator:
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
Exercise:--
Split the string into a list with max 2 items:
txt = "apple#banana#cherry#orange"
print(x)
Python
String partition() Method
The partition() method searches for a specified string, and splits the string
into a tuple containing three elements.
The first element contains the part before the specified string.
Note: This method searches for the first occurrence of the specified string.
Syntax
string.partition(value)
Example
If the specified value is not found, the partition() method returns a tuple
containing: 1 - the whole string, 2 - an empty string, 3 - an empty string:
x = txt.partition("apples")
print(x)