06 String Manipulation 2023-24
06 String Manipulation 2023-24
06 String Manipulation 2023-24
String Manipulation
String: A String is a sequence of characters. In Python string literals are sequence of characters
enclosed in either single or double quotes. eg.
ii.) Multiline Strings: The strings which are written in two or more lines are
called as multiline strings. In Python multiline strings can be created in two
ways:-
a. By adding a back-slash at the end of string and then press Enter key to
continue typing text in the next line.
Example:
After the above statements if you print the value of str1, you will get:
After the above statements if you print the value of str1 you will get:
Notice the \n(newline character) is also added to the string. The symbol
‘\n’ will be displayed when this code is tried in Interactive mode.
1
Traversing a String:
Forward Indexing
Index Numbers 0 1 2 3 4 5
Name P Y T H O N
Index Numbers -6 -5 -4 -3 -2 -1
Backward Indexing
Individual items can be accessed from the String using the Index numbers, for example if you
want to access alphabet ‘T’ then you can write the following print statements:
print(Name[2]) or print(Name[-4])
print(Name)
print(Name[6])
Name[2] = ‘K’
It will show an Error message that “str object does not support item assignment”
because the Strings are immutable.
2
STRING OPERATORS:
1. Basic Operators: The two basic operators of strings are:
a. Concatenation Operator (+): This operator is used to join 2 strings. The few
examples of use of Concatenation operator are as follows:
Input 50 + 100
Output 150
Input “Hello” + 25
Output Error, because String cannot be joined
with numeric value
b. Replication Operator (*): This operator is used to repeat a string. The few examples
of use of Replication operator are as follows:
Input “Hello” * 3
Output ‘HelloHelloHello”
Input 5 * “37”
Output ‘373737’
Input 4 * 60
Output 240
3
2. Membership Operators: The two membership operators are in / not in. These are used
to check whether a particular character or substring appears in a string or not. Both the
operands in Membership Operators should be of string type.
Example:
3. Comparison Operators: All the comparison operators i.e. all Relational Operators (<,
<=, >, >=, = =, !=) apply to strings also. The comparisons using these operators are based
on the standard character-by-character comparison rules for Unicode (i.e. in dictionary
order).
Equality and Non-equality in strings are easier to determine because it goes for
exact character matching for individual letters including the case (upper case or lower
case) of the letter.
Example:
For other comparisons like greater than ( > ) or less than ( < ) Python compares using
Unicode values (also called Ordinal value). Each character in memory is assigned a
unique integer value, called as Ordinal value, through which the character is identified.
The most common characters and their ordinal values are:
ord(single_character)
For example, to know the ordinal value of alphabet a write it in the following way:
Input Ord(“A”)
Output 65
Note: The ord( ) function requires single character only. You may even write an escape
sequence enclosed in single quotes for ord( ) function.
chr( integer_value)
Example:
Input chr(70)
Output F
5
STRING SLICES
String Slice refers to the part of a string. Strings are sliced using a range of indices. The
syntax for slicing a string is:
strname[n : m]
here strname is name of string variable, n is starting index and m is ending index
number. It will return all the characters between n and m-1.
Sample String:
str1 = “Programming”
0 1 2 3 4 5 6 7 8 9 10
P r o g r a m m i n g
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
6
Slicing using combination of forward and backward indexing.
Example:
Input str1[ 4 : 25 ]
Characters at index numbers 4 to 10 are
displayed. It will not display anything for
Output ‘ramming’
index numbers 11 to 25 as these index
numbers are out of bound.
Input str1[ 15 : 25 ]
The output is Empty String, as both the
Output ‘’
index numbers are out of bound.
7
Slicing String in Reverse Order:
To slice the string in reverse order we need to write the starting and ending index
numbers in reverse order and the third index as negative value.
Example:
Input str1[ : : -1 ]
Output ‘gnimmargorP’ The complete string is reversed.
Input str1[ 8 : 2 : -1 ]
String starting from index no. 8 to index
Output ‘immarg’
no. 3, in reverse order.
Input str1[ 10 : 0 : -2 ]
Alternate values starting from index no.
Output ‘gimro’ 10 to index no. 1 in reverse order are
displayed.
8
STRING FUNCTIONS AND METHODS
Python offers many built-in functions and methods for string manipulation. Every
string object created in Python is actually an instance of string class. The different string
functions can be applied to string as per the following syntax:
stringObject.methodName( )
StringObject can either be a string literal or a string variable that holds a string value.
1. string.capitalize( ): This function returns the string with first letter capitalized. If
the string is in upper case then first letter will remain capitalized and all other
characters convert into lower case.
Example:
subject1 = “english"
Input subject 2 = subject1.capitalize( )
subject1
Output ‘english’ String in subject1 remains same.
Input subject2
subject2 contains the string with
Output ‘English’
first letter capitalized.
9
3. string.upper( ): This function returns a copy of the string converted to uppercase.
It doesn’t change the original string, it only coverts and displays the string in
uppercase.
Note: The string may contain numerics, symbols and spaces also.
Example:
email = “[email protected]”
Input
email.upper( )
All lowercase alphabets
Output ‘[email protected]’ converted into uppercase. Digits,
spaces and symbols are allowed.
4. string.title( ): This function returns a copy of the string converted to titlecase i.e.
first letter of each word is capitalized in the string. It doesn’t change the original
string, it only coverts and displays the string in title case.
Note: The string may contain numerics, symbols and spaces also.
Example:
regno = “rj 38 ca 1234”
Input
regno.title( )
First letter of each word is
Output ‘Rj 38 Ca 1234’ capitalized. Digits, spaces and
symbols are allowed.
5. string.islower( ): This function returns True if all the alphabets in the string are
lower case alphabets and there is at least one character, False otherwise.
Note: The string may contain numerics, symbols and spaces also.
10
Example:
email = “[email protected]”
Input
email.islower( )
All alphabets are in lower case,
Output True digits, spaces and symbols are
allowed.
6. string.isupper( ): This function returns True if all the alphabets in the string are
upper case alphabets and there is at least one character, False otherwise.
Note: The string may contain numerics, symbols and spaces also.
Example:
regno = “RJ 38 CA 1234”
Input
regno.isalpha( )
All alphabets are in upper case,
Output True digits, spaces and symbols are
allowed.
7. string.istitle( ): This function returns True if first letter of all the words in the
string is an upper case alphabet and there is at least one character, False
otherwise.
Note: The string may contain numerics, symbols and spaces also.
Example:
11
8. string.isalnum( ): This function returns True if all the characters in the string are
either all alphabets, all numerics or both and there is at least one character,
otherwise False.
Note: If any space or special symbol is used in string then it returns False.
Example:
name = “Ayush”
Input
name.isalnum( )
All characters in string are
Output True
alphabets.
model = “narzo10”
Input
model.isalnum( )
All characters in string are
Output True
alphabets and digits.
9. string.isalpha( ): This function returns True if all the characters in the string are
alphabets and there is at least one character, False otherwise.
Note: If any digit, space or special symbol is used in string then it returns False.
Example:
name = “Ayush”
Input
name.isalpha( )
All characters in string are
Output True
alphabets.
12
10. string.isdigit( ): This function returns True if all the characters in the string are
digits and there is at least one character, False otherwise.
Note: If any alphabet, space or special symbol is used in string then it returns
False.
Example:
session = “2020-21”
Input
session.isdigit( )
String must not contain any
Output False
special symbol.
rollno = “11251”
Input
rollno.isdigit( )
All characters in string are
Output True
digits.
11. string.isspace( ): This function returns True if all the characters in the string are
whitespaces and there is at least one character, otherwise it returns False.
Note: If any alphabet, digit or special symbol is given in string then it returns
False.
Example:
name = “”
Input
name.isspace( )
At least one space is required,
Output False
given string is an Empty string.
subject = “ ”
Input
subject.isspace( )
All characters in string are
Output True
spaces only.
12. string.find( ): This function finds a substring in a string and returns the index
number of its first occurrence.
You can specify Start and End as starting and ending index numbers
where you want to look for the substring.
This function returns –1 if substring is not found.
13
Example:
13. string.index( ): This function is similar to find function. It checks for a substring
in a string and returns the index number of its first occurrence.
You can specify Start and End as starting and ending index numbers
where you want to look for the substring.
This function displays Error message if substring is not found.
Example:
14
14. string.count( ): This function counts and returns the number of occurrences of a
substring in a string.
Example:
15. string.startswith( ): This function returns True if the string starts with the given
substring, otherwise returns False.
Example:
16. string.endswith( ): This function returns True if the string ends with the given
substring, otherwise returns False.
Example:
17. string.replace( ): This function replaces a substring in the string with the given
substring.
Example:
15
18. string.strip( ): This function returns copy of the string after removing the
specified characters from the beginning and end of the string. It removes the
specified characters from the left and right of the string. The specified characters
may appear in any order but in string to remove the specified characters, those
must be in continuation. To the left and right of the string one or more specified
characters may appear in any order.
Note: If strip( ) is used without any argument, it removes the leading and trailing
whitespaces.
Example:
19. string.lstrip( ): This function returns copy of the string after removing the
specified characters from the beginning of the string. It removes the specified
characters from the left of the string. The specified characters may appear in any
order but in string to remove the specified characters, those must be in
continuation. To the left of the string one or more specified characters may
appear.
Note: If lstrip( ) is used without any argument, it removes the leading
whitespaces.
Example:
20. string.rstrip( ): This function returns copy of the string after removing the
specified characters from the end of the string. It removes the specified characters
from the right of the string. The specified characters may appear in any order but
in string to remove the specified characters, those must be in continuation. To the
ritht of the string one or more specified characters may appear.
16
Example:
movie = “fast and furious”
Input
movie.rstrip(“sufa” )
Output ‘fast and furio’ From right side ‘us’ is removed.
21. string.split( ): This function splits (divides) a string in multiple parts from the
given substring or character. The substring which is used to split the string into
parts is not displayed in the output. The split strings are shown in a list form.
Example:
22. string.partition( ): This function partitions a string in two parts from the given
substring. It returns 3 strings as result: First string contains characters to the left of
given substring, Second string is the given substring itself and the Third string
contains the characters to the right of the given substring.
Example:
23. string.join( ): This function joins a string or character after each character of the
string or each element of the list (except the last character of the string).
Example:
name = “Kartik”
Input
“**”.join( name )
After each character of name the
Output ‘K**a**r**t**i**k’
substring ‘**’ is added.
cartoon = [“Tom”,“and”,“Jerry”]
Input
“@@@”.join( cartoon )
After each element of the list
Output ‘Tom@@@and@@@Jerry’
substring ‘@@@’ is added.
----- X -----
17