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

String Manipulation

This document provides an overview of string manipulation in Python, covering definitions, creation, and various operations such as concatenation, slicing, and string methods. It explains concepts like immutability, membership, and comparison operators, along with examples and sample programs for practice. Additionally, it includes programming tasks for students to enhance their understanding of string manipulation.

Uploaded by

ritamdawn01
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)
4 views

String Manipulation

This document provides an overview of string manipulation in Python, covering definitions, creation, and various operations such as concatenation, slicing, and string methods. It explains concepts like immutability, membership, and comparison operators, along with examples and sample programs for practice. Additionally, it includes programming tasks for students to enhance their understanding of string manipulation.

Uploaded by

ritamdawn01
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/ 16

Class 11

String Manipulation…Python…
For Computer Science students’
Hopefully, all of you go through the previous uploaded materials. In this material we discuss about “String
Manipulation - Python”

You all have basic knowledge about Python strings.

Now the questions arises,

Where have we seen strings before?

And the answer is YES. We have seen strings before.

Let’s recall a program that we have discussed in the previous materials.

A program to display “Welcome To Python” message to the user combines with his / her name.

Consider the python code for this:

If we look at the output of the above program:

So, all of you have the basic idea of strings.

What are strings:-


Python strings are consecutive sequence of characters, which are enclosed in quotes of any type like single quotation,
double quotation or triple quotation marks. This sequence of characters may include a letter, a number, special character
etc. Strings are immutable.

Python treats single quotes the same as double quotes i.e. you can use any of them.

But triple quotes are typically used for strings that span multiple lines.
Examples of strings:
‘Python is a programming language’ - single line string single quotes is used

“Python is a very popular language” - single line strings double quotes is used

‘ram’ or “ram” - string enclosed by single or double quotes

“ram12”

‘abc_123’

“Kolkata 26”

Creation of strings:
Creation of strings in python is very easy.

e.g.

a = “computer science”  here variable a holds a string

b = ‘class 11’  here variable b holds a string

Empty string:
An empty string is a string without any characters inside.

x = “” or x = ‘’  here x contains an empty string

Note: if a command is long, then it can be shifted to the next line by typing ‘\’, but it shows the result in the same line.

Output:

On the above example backslash ( \ ) is an escape sequence that’s why the output is shown in same line.

If you wish to display the output in the next line, then you use the ‘\n’ escape sequence as follows:

Output:
Multiline strings:
Multiline strings are represented using triple quotes.

Example:

Output:

Traversing a string:
Traversing a string means iterating through the elements of a string, one character at a time.

To traverse through a string, you can write a loop like:

and the output is:

If you want to display the output

in a single line separated by ‘hyphen’, then your code:

Output:

You can also write the above code by using while loop as follows:

(Note: to determine the number of iteration you have to use the len( ) function to find the length of the string.)

Before writing the program, first go through the character representation of the above string in memory.

x = “Computer Science”
All of you know that each character in a string has an index value. Indexing starts at 0.

Now, if you want to write the above program by using while loop then you first determine – How many times your loop
will be executed?

Yes….. the answer is 16

How do you know that?

As indexing starts at 0 and ends at 15 in the above case, so number of iteration required is 16.

To avoid counting by ourselves we use len( ) function for finding the length. Just look at the following code:

Output:

See, len( ) shows the length is 16. But actually in 16th position is not in the above string. The actual indexing is from 0 to
15.

Ok….. Now, we traversing a string using while loop:

Output:

Ok?

Look at the condition statement of the above loop:

while i < a: as we want to execute the loop from 0 to 15

here first we set i = 0 and

a = len(x) indicates a = 16
so i < a or you can use i <= a - 1

Look at the print( ) statement of the above loop:

print(x[i] , end = ‘-’)


Think……. why x[i] ?

If you write i instead of x[i] then see what will happen?

Not expected result as i


indicates the position not
the value on that position

Output:

Let’s try to write a program that read a string from the user and display it in reverse order.

Program: using for loop

Output:

Explanation: x = “Python World” , a = len(x) i.e. a = 12

but the actual representation is:

We know, the for loop is working like following:

for i in range (1, 5):  it indicates the iterations : 1, 2, 3, 4

i.e. in general for i in range(1, n):  indicates iterations from 1 to n – 1

if, we write: for i in range(5, 1, -1):  it indicates the iterations: 5, 4, 3, 2 ( -1 indicates the steps)
So, in our program, we want to print the string x in reverse order i.e. (from the length) -1 to 0

therefore we use:
step value
for i in range (a -1 , -1, -1)

Let’s try the same program of reverse a string using while loop:-

Output:

String Operators:
 Basic Operators:

1) string concatenation operator +


The + operator creates a new string by joining two operand strings.

Example:

“Tea” + “pot”  it produce “Teapot” by joining

“Kolkata” + “700012”  it produce “Kolkata700012”

Think over the output of:

2+3 and “2” + “3”

2) string replication operator *


The * operator creates a new string that is a number of repetitions of a string.

Example:

3 * “Go”  it produce “GoGoGo”

‘a’ * 5  it produce ‘aaaaa’

Think over the output of:

2*3 and “2” * 3


 Membership Operators:

Two membership operators for strings:


1) in  returns True if a character or substring exists in the given string; False otherwise
2) not in  returns True if a character or substring does not exists in the given string; False otherwise

Example:
“a” in “keya”  will give True
“a” in “sunil”  will give False

“jap” not in “japan”  will give False


“123” not in “hello”  will give True

 Comparison Operators:

all relational operators of python apply to strings also.

Example:
“a” = = “a”  will give True
‘Ram’ = = ‘ram’  will give False

‘a’ != ‘abc’  will give True


“A” != ‘a’  will give True

“ABC” != “abc”  will give False

‘A’ > ‘a’  will give False


‘a’ > ‘b’  will give False

‘abcd’ > ‘abcD’  will give True ( as ‘abc’ in both strings are equal but ‘d’ is always greater
than ‘D’

Computer actually compare between characters based on their ordinal values.


Common characters and their ordinal values are follows:

Characters ordinal values


‘0’ to ‘9’ (digits) 48 to 57
‘A’ to ‘Z’ (uppercase alphabets) 65 to 90
‘a’ to ‘z’ (lowercase alphabets) 97 to 122

Determining ordinal values and character values:-


If you want to use the ordinal or the character values in your program the python provides two functions to
determine ordinal and character values as follows:
ord( ) :- determines the ordinal value of a character.
Example: ord(‘A’)  it will give 65
ord(‘9’)  it will give 57
chr( ) :- returns the character based on the corresponding integer ordinal value.
Example: chr(98)  it will give ‘b’
ord(50) it will give ‘2’
 string slicing:

‘string slice’ refers to a part of string, where the string is sliced using a range of indices.

To understand this, we look at the memory representation of a string using its indices again:

x = “amazing world”

then the representation of x in memory:

Then,
x[ 0 : 7 ]  will give “amazing”
x[ 0 : 3 ]  will give “ama”
x[ 2 : 5 ]  will give “azi”
x[ 4 : 10]  will give “ing wo”

x[ -7 : -3]  will give “g wo”


x[ -5 : -1]  will give “worl”

x [ : 11 ]  will give “amazing wor” ( as first index is missing so it starts from 0)


x[5: ]  will give “ng world” (as last index is missing so it ends at last of the string)
x[ : ]  will give “amazing world” ( as two indices are missing so it prints the whole string)

String Functions and Methods:


Python also offers many built-in functions and methods for string manipulation.

1) len( ) : - this method returns the length of the string.

syntax: len(string)

Example: Output:

2) capitalize( ) : - this method returns the exact string with the first letter in uppercase.

syntax: string.capitalize( )

Example: Output:
3) find( ) : - returns the lowest index in the string where the substring is found within the slice range of start and stop.
syntax: string.find( substring, start, stop)

Example:

Output:

(Note: -1 indicates the substring is not present)

4) isalnum( ) : - returns True if the character in the string are alphanumeric (alphabets or numbers). False otherwise.

syntax: string.isalnum( )

Example: Output:

5) isalpha( ) : - returns True if all characters in the string are alphabetic. False otherwise.

syntax: string.isalpha( )
Example: Output:

6) isdigit( ) : - returns True if all characters in the string are digits. False otherwise.

syntax: string.isdigit( )

Example: Output:

7) islower( ) : - returns True if all characters in the string are lowercase. False otherwise.
syntax: string.islower( )

Example: Output:
8) isupper( ) : - returns True if all characters in the string are uppercase. False otherwise.
syntax: string.isupper( )

Example: Output:

9) isspace( ) : - returns True if there is only whitespace characters. False otherwise.


syntax: string.isspace( )

Example: Output:

10) lower( ) : - returns a copy of the string converted into lowercase.


syntax: string.lower( )

Example: Output:

10) upper( ) : - returns a copy of the string converted into uppercase.

syntax: string.upper( )

Example: Output:
11) lstrip( ) : - returns a copy of the string with leading characters removed.
syntax: string.lstrip( )

Example:

Output:

12) rstrip( ) : - returns a copy of the string with trailing characters removed.
syntax: string.rstrip( )

Example:

Output:

13) split( ) : - breaks up a string at the specified separator and returns a list of substrings.

syntax: string.split( separator, maximum spliting)

Example:

Output:
14) replace( ) : - replaces all the occurrences of the old string with the new string.
syntax: string.replace( oldstring, newstring)

Example:

Output:
replaces all occurrences of “is”

Strings are immutable:-


All of you know that strings are immutable that means the content of the string cannot be changed after it has been
created.
Let us understand the concept of immutability with help of the following example:

When you want to run the above program it shows the following error:

So, you cannot modify the contents of a string after it has been created.

Sample Program Examples:-


Program 1) Write a program to find the length of a string without using len( ) function.
Solution:

Output:
Program 2) Write a program to count the number of vowels present in a given string.
Solution:

Output:

Program 3) Write a program to count the number of words present in the given string and also display each
word.
Solution:

Output:

Program 4) Write a program to count the number of lowercase and uppercase alphabets present in the given
string.
Solution:

Output:
Program 5) Write a program that takes a string from the user and display the occurrence of words starting with
a vowel in the given string also counts those words.
Solution:

Output:

Program 6) Write a program that takes a word from the user and check that the word is palindrome word or
not.
Example of palindrome word is: MADAM
i.e. the original word and the reverse word is same
Solution: Output:
Program 7) Write a program that reads a string nd display the longest substring of the given string.
Solution:

Output:

Programming Tasks:
1) Write a program that reads a given string and display the number of uppercase letters, number of lowercase letters,
number of alphabets, number of spaces and number of digits are present in the given string.
2) Write a program that reads a given string, counts how many times a substring “is” appears in the given string.
3) Write a program that reads a string from the user then converts each lowercase alphabet to uppercase and all
uppercase alphabets to lowercase. ( Hint: use islower( ), isupper( ), lower( ) and upper( ) function)
4) Write a program that reads a string then prints a string that capitalizes every other letter in the string.
Example: If the given string is: passion
then the resulted string will be: pAsSiOn
5) Write a program that reads a string from the user then prints a string after removing all vowels from the given string.
6) Write a program that reads a string from the user then counts how many words are starting with ‘s’ or ‘S’.
7) Write a program that reads a string from the user then calculates the sum of each digit present in the given string.

Read the whole materials carefully…..


Practice all solved programming examples.
Try to solve all programming tasks.
For any problem message or call me

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy