PPS NOTES Unit-4.
PPS NOTES Unit-4.
Strings
A string is a data structure in Python that represents a sequence of characters. It is an immutable data type,
meaning that once you have created a string, you cannot change it. Python does not have a character data type, a
single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the
0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called
the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python
allows us to use single quotes, double quotes, or triple quotes to create the string.
Example in Python to create a string. 799
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script Features of Java -
Note:-In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-
quotes to represent the string, but it is generally used for multiline string or docstrings.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
--------------------------------------------*********************--------------------------------------------
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
Output:
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we
can use the : (colon) operator in Python to access the substring from the given string. Consider the following
example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO' is
given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
Consider the following example:
# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The
second rightmost index indicates -2, and so on. Consider the following image.
str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Output:
------------------------------------***********************---------------------------------------------
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item
assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced.
Strings are immutable in Python.
Consider the following example.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
Output:
However, in example 1, the string str can be assigned completely to a new content as specified in the following
example.
Example 2
str = "HELLO"
print(str)
str = "hello"
print(str)
Output:
-------------------------------------------*********************-----------------------------------------
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string. But we can
delete the entire string using the del keyword.
str = "JAVATPOINT"
del str[1]
Output:
str1 = "JAVATPOINT"
del str1
print(str1)
Output:
----------------------------------------**********************---------------------------------------------
String Operators:-
Operator Description
+ It is known as concatenation operator used to join the strings given either side of
the operator.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
not in It is also a membership operator and does the exact reverse of in. It returns true if
a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we
need to print the actual meaning of escape characters such as "C://python". To
define any string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used
in C programming like %d or %f to map their values in python. We will discuss
how formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
Membership Operators
Membership operators are operators used to validate the membership of a value. It tests for membership in a
sequence, such as strings, lists, or tuples.
in operator: The The in operator in Python can be used to check if a specific substring or character exists
within a larger string. Evaluate to true if it finds a variable in the specified sequence and false otherwise.
Example:
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s in 'I saw The Holy Grail!'
False
#Output: Found: The substring 'world' was found in the string 'Hello, world!'.
#Example:
# Python program to illustrate 'in' operator
string = "Hello, world!"
char = "o"
if char in string:
print("Found")
else:
print("Not Found")
#Output: Found: The char 'o' was found in the string 'Hello, world!'.
‘not in’ operator- Evaluates to true if it does not finds a variable in specified sequence and false otherwise.
>>> s = 'spam'
>>> s not in 'I saw The Holy Grail!'
True
>>> s not in 'I saw spamalot!'
False
#Output: Not Found: The substring 'world' was found in the string 'Hello, world!'.
#Example:
# Python program to illustrate 'in' operator
string = "Hello, world!"
char = "o"
if char not in string:
print("Found")
else:
print("Not Found")
#Output: Not Found: The char 'o' was found in the string 'Hello, world!'.
---------------------------------------****************************------------------------------------
Python String Formatting:-
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can be
written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-
quotes.
Example
Consider the following example to understand the real use of Python operators.
str = "They said, "Hello what's going on?""
print(str)
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it
interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the
double quotes.
Example -
Output:
2. \\ Backslash print("\\")
Output:
\
print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")
Output:
We can ignore the escape sequence from the given string by using the raw string. We can do this by
writing r or R in front of the string. Consider the following example.
print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
-----------------------------------------------*******************----------------------------------------
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:
Output:
My name is Ashutosh.
This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and
you can even do arithmetic operations in it.
Example: Arithmetic operations using F-strings
a = 5
b = 10
print(f"He said his age is {2 * (a
+ b)}.")
Output:
He said his age is 30.
We can also use lambda expressions in f-string formatting. Example: Lambda Expressions using F-strings
--------------------------------------------*************************-----------------------------------------
Method Description
center(width ,fillchar) It returns a space padded string with the original string
centred with equal number of left and right spaces.
decode(encoding = 'UTF8', errors Decodes the string using codec registered for encoding.
= 'strict')
find(substring ,beginIndex, It returns the index value of the string where substring is
endIndex) found between begin index and end index.
isalpha() It returns true if all the characters are alphabets and there
is at least one character, otherwise False.
isdigit() It returns true if all the characters are digits and there is
at least one character, otherwise False.
partition() It searches for the separator sep in S, and returns the part
before it, the separator itself, and the part after it. If the
separator is not found, return S and two empty strings.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the
backward direction. It returns the list of words in the
string. If Separator is not specified then the string splits
according to the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string
splits according to the space if the delimiter is not
provided. It returns the list of substring concatenated
with the delimiter.
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
rpartition()
---------------------------------------*************-----------------------------------------------------
Strings Concatenations:-
Python string is a collection of Unicode characters. Python provides many built-in functions for string
manipulation. String concatenation is a process when one string is merged with another string. It can be done in
the following ways.
Using + operators
Using join() method
Using % method
Using format() function
Let's understand the following string concatenation methods.
Using + operator
This is an easy way to combine the two strings. The + operator adds the multiple strings together. Strings must be
assigned to the different variables because strings are immutable. Let's understand the following example.
Example -
# Defining strings
str1 = "Hello "
str2 = "Python"
Output:
Hello Python
Explanation:
In the above example, the variable str1 stores the string "Hello", and variable str2 stores the "Devansh". We used
the + operator to combine these two string variables and stored in str3.
Using join() method
The join() method is used to join the string in which the str separator has joined the sequence elements. Let's
understand the following example.
words = ["hello", "world"]
delimiter = " "
sentence = delimiter.join(words)
print(sentence)
Example -
print(str3)
Output:
Hello Kaustubh Tripathi
Hello Kaustubh Tripathi
Explanation:
In the above code, the variable str1 stores the string "Hello" and variable str2 stores the " Kaustubh Tripathi".
The join() method returns the combined string that is stored in the str1 and str2. The join() method takes only list
as an argument.
Using % Operator
The % operator is used for string formatting. It can also be used for string concatenation. Let's understand the
following example.
Example -
# Python program to demonstrate
# string concatenation
str1 = "Hello"
str2 = "Kaustubh"
Hello Kaustubh
Explanation -
In the above code, the %s represents the string data-type. We passed both variables's value to the %s that
combined the strings and returned the "Hello Kaustubh".
Using format() function:-
Python provides the str.format() function, which allows use of multiple substitutions and value formatting. It
accepts the positional arguments and concatenates the string through positional formatting. Let's understand the
following example.
Example -
str1 = "Hello"
str2 = "ISBM"
Explanation:
In the above code, the format() function combines both strings and stores into the str3 variable. The curly braces
{} are used as the position of the strings.
-----------------------------------------------**********************----------------------------------------
Appending of Strings:-
As we know, the object of the string is immutable when we use the “+” operator for concatenating strings, a new
different string is created. Whereas the appending of the string is just to modify the original string, which is also
similar to using the “+” operator. This append function is mostly used on a list of strings. To repeatedly append
the strings, we need to first convert it into a list, then append the given elements to that list, and then join the list
back to the appended string.
Now let us see how to append a string using the “+” operator, which is also known as a concatenation of strings.
Let us see the below example, which uses the “+” operator for concatenating the given string.
Example:
str1 = "ISBM, PUNE"
str2 = " COE, PGDM"
print("The given original string : " + str(str1))
print("The string given to append to the previous string: " +
str(str2))
res = str1 + str2
print("The Modified string is obtained as follows:")
print(res)
Output
In the above program, we have seen that there are two strings, “str1” and “str2,” where str1 is appended with str2
using the “ +“ operator. This is done in the statement “res = str1 + str2,” where we are adding string 1to strin2 to
obtain the result, which is stored in the variable “res.” The result is the addition of two strings, or we can say str2
is appended to str1. We can see str2 starts with white space so that when it is appended to the str1, we can read it
properly.
Now let us see how to use the append() function to append two strings. This function also works similarly to the
“+” operator as above. Let us see the below example using the append() function. This function is mainly used to
append more than two strings.
Syntax:
str.append(items)
Where item which is to be added to the list of strings. This will add a single item to the given string or list of
strings.
Example:
str1 = ['ISBM', 'COE', 'PUNE']
print("The first string list is given as follows:")
print(str1)
str2 = ['MAHARASTRA', 'INDIA']
print("The second string list that needs to be appneded to the first string list is as follows")
print(str2)
str1.append(str2)
print("The modified string list after appending is as follows:")
print(str1)
Output
In the above program, we can see we have two string lists where str2 needs to be appended to the str1, and the
result is obtained with one single string having the second string appended to it.
--------------------------------------********************---------------------------------------------------
print('Hello' * 5)
Output
HelloHelloHelloHelloHello
# String slicing
String ='ASTRING'
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way
to slice a string both syntax wise and execution wise.
Syntax
string[start:end:step]
Note:- start, end and step have the same mechanism as slice() constructor.
Example # Python program to demonstrate
# string slicing
# String slicing
String ='ASTRING'
# Using indexing sequence
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
Output:
-----------------------------------------------***********************-----------------------------------------------
ord(character)
Note: If the string length is more than one, and a TypeError will be raised. The syntax can be ord(“a”) or
ord(‘a’), both will give same results.
Example
# inbuilt function return an
# integer representing the Unicode code
value = ord("A")
# Raises Exception
value1 = ord('AB')
chr() functions:
The chr() method returns a string representing a character whose Unicode code point is an integer.
Syntax: chr(num)
num : integer value
Output:
65
A
---------------------------------------****************************------------------------------------------
in and not in operators:
The in operator can be used to check if a substring is present within a string. For example:
# use of in membership operator
Output:
Substring found in string.
# use of not in membership operator
str1 += "o"
str4 = "Hello"
Output:
ID of str1 = 0x7f1b492481b0
ID of str2 = 0x7f1b492481b0
ID of str3 = 0x7f1b492481b0
True
True
True
for i in range(len(str1)):
if str1[i] >= "0" and str1[i] <= "9":
count1 += 1
for i in range(len(str2)):
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1
print(compare_strings("123", "12345"))
print(compare_strings("12345", "hello"))
print(compare_strings("12hello", "hello12"))
Output:
False
False
True
--------------------------------------------***************------------------------------------------
# Code #2
string_name = "Shreeram"
Shreeram Tripathi
S
h
r
e
e
r
a
m
Example #2: Using enumerate() function: the string is an array, and hence you can loop over it. If you pass a
string to enumerate(), the output will show you the index and value for each character of the string .
# Python program to iterate over characters of a
string
string_name = "Shreeram"
Output:
S
h
r
e
e
r
a
m
Example #3: Iterate characters in reverse order
# Python program to iterate over characters of a string
# Code #1
string_name = "SHREERAM"
# slicing the string in reverse fashion
for element in string_name[ : :-1]:
print(element, end =' ')
print('\n')
# Code #2
string_name = "SHREERAM TRIPATHI"
I
H
T
A
P
I
R
T
M
A
R
E
E
R
H
S
Example #4: Iteration over particular set of element.
# Python program to iterate over particular set
of element.
# string_name[start:end:step]
for element in string_name[0:8:1]:
print(element,end =' ')
Output:
S h r e e r a m
----------------------------------------**************************--------------------------------------
String module:
The string module in Python is a built-in module that provides a collection of useful string
operations and constants.
Some of the commonly used functions and constants in the string module include:
string.ascii_letters: A string containing all letters (both uppercase and lowercase) in the
ASCII character set.
string.ascii_lowercase: A string containing all lowercase letters in the ASCII character set.
string.ascii_uppercase: A string containing all uppercase letters in the ASCII character set.
string.digits: A string containing all digits (0-9) in the ASCII character set.
string.hexdigits: A string containing all hexadecimal digits (0-9 and A-F) in the ASCII
character set.
string.octdigits: A string containing all octal digits (0-7) in the ASCII character set.
string.punctuation: A string containing all punctuation characters in the ASCII character
set.
string.whitespace: A string containing all whitespace characters in the ASCII character set.
string.capwords(s): Capitalize the first letter of each word in a string.
string.maketrans(x[, y[, z]]): Returns a translation table usable for str.translate().
string.Template(template): A class for creating simple templates.
Reference: https://docs.python.org/3/library/string.html
----------------------------------------**************************--------------------------------------
String Programs:
def string_length(string):
count = 0
for char in string:
count += 1
return count
or
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
string=raw_input("Enter string:")
count=0
for i in string:
if(i.islower()): #isupper() for comparing upper case
count=count+1
print("The number of lowercase characters is:")
print(count)
string=raw_input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)