0% found this document useful (0 votes)
6 views

[CH-6] String Manipulation

The document provides an extensive overview of string manipulation in Python, including various methods for extracting substrings, reversing strings, creating sublists, and filtering elements. It covers string formatting, built-in methods for modifying strings, and checks for character types, along with practical examples for each concept. Additionally, it explains slicing, concatenation, and the use of escape characters in strings.

Uploaded by

jiya23022009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

[CH-6] String Manipulation

The document provides an extensive overview of string manipulation in Python, including various methods for extracting substrings, reversing strings, creating sublists, and filtering elements. It covers string formatting, built-in methods for modifying strings, and checks for character types, along with practical examples for each concept. Additionally, it explains slicing, concatenation, and the use of escape characters in strings.

Uploaded by

jiya23022009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

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

full_name = "John Doe"


first_name = full_name[:full_name.index(" ")]
last_name = full_name[full_name.index(" ") + 1:]

Use code with caution.

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]

Use code with caution.

3. Creating Sublists:
o Scenario: You're analyzing a list of sales data and want to extract specific
time periods.
o Code:

Python

sales_data = [100, 200, 300, 400, 500]


first_quarter_sales = sales_data[:3]

Use code with caution.

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

email_addresses = ["[email protected]", "[email protected]",


"[email protected]"]
com_addresses = [email for email in email_addresses if
email.endswith(".com")]

Use code with caution.

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.

'hello' is the same as "hello".

You can display a string literal with the print() function:

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:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""

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!"

for character in my_string:


print(character)

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.

2.Method using built-in reversed method:

 INPUT
string="python"
for i in reversed(string):
print(i,end=" ")

 OUTPUT:

nohtyp

 Python - Slicing Strings


 Slicing
 You can return a range of characters by using the slice syntax.
 Specify the start index and the end index, separated by a colon, to return a part of the
string.

Example
 Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.


Slice From the Start
 By leaving out the start index, the range will start at the first character:

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:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

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:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

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.

To specify a string as an f-string, simply put an f in front of the string literal,


and add curly brackets {} as placeholders for variables and other operations.

Example
Create an f-string:

age = 36
txt = f" My name is John, I am {age}"
print(txt)

 ESCAPE Character :-

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to


insert.

An example of an illegal character is a double quote inside a string that is


surrounded by double quotes:

To fix this problem, use the 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:

txt = "We are the so-called \"Vikings\" from the north."


 Newline character:-

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:

txt = "python is FUN!"

x = txt.capitalize()

print (x)
OUTPUT:-

Example
See what happens if the first character is a number:

txt = "36 is my age."

x = txt.capitalize()

print (x)

Python String title() Method


The title() method returns a string where the first character in every word
is upper case. Like a header, or a title.

If the word contains a number or a symbol, the first letter after that will be
converted to upper case.

Syntax
string.title()

Example
Make the first letter in each word upper case:

txt = "Welcome to my world"

x = txt.title()

print(x)

OUTPUT:-

Welcome To My World

Exercise:-
txt = "hello b2b2b2 and 3g3g3g"

x = txt.title()

print(x)

Python String index() Method


The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.

The index() method is almost the same as the find() method, the only
difference is that the find() method returns -1 if the value is not found. (See
example below)

Syntax
string.index(value, start, end)

 Example
Where in the text is the first occurrence of the letter "e"?:

txt = "Hello, welcome to my world."

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?:

txt = "Hello, welcome to my world."

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

print(x)

 Difference between index() vs find() :-

Example
If the value is not found, the find() method returns -1, but the index()
method will raise an exception:

txt = "Hello, welcome to my world."

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

Python String find() Method


The find() method finds the first occurrence of the specified value.

The find() method returns -1 if the value is not found.

The find() method is almost the same as the index() method, the only
difference is that the index() method raises an exception if the value is not
found. (See example below)

Syntax
string.find(value, start, end)

Example
Where in the text is the word "welcome"?:

txt = "Hello, welcome to my world."

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:

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

x = txt.count("apple")

print(x)

Example
Search from position 10 to 24:

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

x = txt.count("apple", 10, 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 (.):

txt = "Hello, welcome to my world."

x = txt.endswith(".")

print(x)

Exercise
Check if position 5 to 11 ends with the phrase "my world.":

txt = "Hello, welcome to my world."

x = txt.endswith("my world.", 5, 11)

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":

txt = "Hello, welcome to my world."

x = txt.startswith("Hello")
print(x)

Exercise:-
Check if position 7 to 20 starts with the characters "wel":

txt = "Hello, welcome to my world."

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).

Example of characters that are not alphabet letters: (space)!#%&? etc.

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).

Example of characters that are not alphanumeric: (space)!#%&? etc.

Syntax
string.isalnum()

Example
Check if all the characters in the text are alphanumeric:

txt = "Company12"

x = txt.isalnum()

print(x)

EXERCISE:--

Check if all the characters in the text is alphanumeric:

txt = "Company 12"

x = txt.isalnum()

print(x)
Python
String isdigit() Method
The isdigit() method returns True if all the characters are digits, otherwise
False.

Exponents, like ², are also considered to be a digit.

Syntax
string.isdigit()

 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:

a = "\u0030" #unicode for 0


b = "\u00B2" #unicode for ²

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:

txt = "hello world!"

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:

txt = " "

x = txt.isspace()

print(x)
OUTPUT:-

True

Exercise:---
Check if all the characters in the text are whitespaces:

txt = " s "

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:

txt = "THIS IS NOW!"

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())

Python String lstrip() Method


Definition and Usage
The lstrip() method removes any leading characters (space is the default
leading character to remove)

Syntax
string.lstrip(characters)

Example
Remove spaces to the left of the string:

txt = " banana "

x = txt.lstrip()

print("of all fruits", x, "is my favorite")

OUTPUT:-
of all fruits banana is my favorite

Exercise:-
Remove the leading characters:
txt = ",,,,,ssaaww.....banana"

x = txt.lstrip(",.asw")

print(x)

Python String rstrip() Method


The rstrip() method removes any trailing characters (characters at
the end a string), space is the default trailing character to remove.

Syntax
string.rstrip(characters)

EXAMPLE:-

txt = " banana "

x = txt.rstrip()

print("of all fruits", x, "is my favorite")

OUTPUT:-

of all fruits banana is my favorite.

Exercise:---
Remove the trailing characters if they are commas, periods, s, q, or w:

txt = "banana,,,,,ssqqqww....."

x = txt.rstrip(",.qsw")

print(x)

Python String strip() Method


The strip() method removes any leading, and trailing whitespaces.

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:

txt = " banana "

x = txt.strip()

print("of all fruits", x, "is my favorite")

Exercise:
Remove the leading and trailing characters:

txt = ",,,,,rrttgg.....banana....rrr"

x = txt.strip(",.grt")

print(x)

Python String join() Method


The join() method takes all items in an iterable and joins them into one
string.

A string must be specified as the separator.

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:

myDict = {"name": "John", "country": "Norway"}


mySeparator = "TEST"

x = mySeparator.join(myDict)

print(x)

Note: When using a dictionary as an iterable, the returned values are the
keys, not the values.

Python String split() Method


The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

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:

txt = "welcome to the jungle"

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"

# setting the maxsplit parameter to 1, will return a list with 2


elements!
x = txt.split("#", 1)

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.

The second element contains the specified string.


The third element contains the part after the 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:

txt = "I could eat bananas all day"

x = txt.partition("apples")

print(x)

You might also like