Module 3 Strings Solutions
Module 3 Strings Solutions
STRINGS
Strings are sequences of characters. Your name can be considered a string. Or, say
you live in Zambia, then your country name is "Zambia", which is a string.
In this tutorial you will see how strings are treated in Python, the different ways in
which strings are represented in Python, and the ways in which you can use strings
in your code.
To create a string, put the sequence of characters inside either single quotes,
double quotes, or triple quotes and then assign it to a variable. You can look into
how variables work in Python in the Python variables tutorial.
For example, you can assign a character ‘a’ to a
variable single_quote_character. Note that the string is a single character and
it is “enclosed” by single quotes.
Also check out if you can assign a sequence of characters or multiple characters to
a variable. You can assign both single quote sequences and double quote
sequences.
Interestingly if you check the equivalence of one to the other using the keyword is,
it returns True.
>>> print(double_quote_multiple_characters is
double_quote_multiple_characters)
True
Take a look at assignment of strings using triple quotes and check if they belong to
the class str as well.
In the examples above, the function type is used to show the underlying class that
the object will belong to. Please note that all the variables that have been initiated
with single, double, or triple quotes are taken as string. You can use single and
double quotes for a single line of characters. Multiple lines are generally put in triple
quotes.
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
• Python3
# Python Program to
# Creating a String
String1 = "GeeksForGeeks"
print(String1)
print(String1[3:12])
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks
As we know, indexes are used in arrays in all the programming languages. We can access the
elements of an array by going through their indexes. But no programming language allows us to use a
negative index value such as -4. Python programming language supports negative indexing of arrays,
something which is not available in arrays in most other programming languages. This means that the
index value of -1 gives the last element, and -2 gives the second last element of an array. The negative
indexing starts from where the array ends. This means that the last element of the array is the first element
in the negative indexing which is -1.
Example:
a = [10, 20, 30, 40, 50]
print (a[-1])
print (a[-2])
Output:
50
40
In Python, list slicing is a common practice and it is the most used technique for
programmers to solve efficient problems. Consider a python list, In-order to access
a range of elements in a list, you need to slice a list. One way to do this is to use
the simple slicing operator i.e. colon(:)
With this operator, one can specify where to start the slicing, where to end, and
specify the step. List slicing returns a new list from the existing list.
Syntax:
Lst[ Initial : End : IndexJump ]
Slicing
As mentioned earlier list slicing is a common practice in Python and can be used
both with positive indexes as well as negative indexes. The below diagram
illustrates the technique of list slicing:
The below program transforms the above illustration into python code:
• Python3
# Initialize list
# Display list
print(Lst[1:5])
print(Lst[3:-1])
Output:
[70, 30, 20, 90]
[20, 90, 10]
4.Is String a mutable data type? Explain it with suitable example.
a = "messi"
for i in a:
if i =='m':
m='b'
print(a)
OUTPUT:
messi
len() is a built-in function in python. You can use the len() to get the length of the
given string, array, list, tuple, dictionary, etc.
You can use len function to optimize the performance of the program. The number
of elements stored in the object is never calculated, so len helps provide the number
of elements.
str_object[start_pos:end_pos:step]
The slicing starts with the start_pos index (included) and ends at end_pos index
(excluded). The step parameter is used to specify the steps to take from start to end
index.
Python String slicing always follows this rule: s[:i] + s[i:] == s for any index ‘i’.
All these parameters are optional – start_pos default value is 0, the end_pos default
value is the length of string and step default value is 1.
s = 'HelloWorld'
first_five_chars = s[:5]
print(first_five_chars)
third_to_fifth_chars = s[2:5]
print(third_to_fifth_chars)
Output:
Hello
llo
In python, String operators represent the different types of operations that can be employed on the
program’s string type of variables. Python allows several string operators that can be applied on the python
defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name = “string” assigns
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
Example #2 – Concatenate Operator “+.”
Two strings can be concatenated or join using the “+” operator in python, as explained in the below
example code:
Code:
string1 = "hello"
string_combined = string1+string2
print(string_combined)
Output:
Code:
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
Output:
interpreted as a positive index starting from 0 from the left side and a negative index starting from -1 from
String H E L L O W O R L D
Positive index 0 1 2 3 4 5 6 7 8 9
• string[a]: Returns a character from a positive index a of the string from the left side as displayed in
• string[-a]: Returns a character from a negative index a of the string from the right side as displayed
• string[a:b]: Returns characters from positive index a to positive index b of the as displayed in index
graph above.
• string[a:-b]: Returns characters from positive index a to the negative index b of the string as
• string[a:]: Returns characters from positive index a to the end of the string.
• string[:b] Returns characters from the start of the string to the positive index b.
• string[-a:]: Returns characters from negative index a to the end of the string.
• string[:-b]: Returns characters from the start of the string to the negative index b.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
Example #5 – String Comparison Operator “==” & “!=”
The string comparison operator in python is used to compare two strings.
• “==” operator returns Boolean True if two strings are the same and return Boolean False if two
• “!=” operator returns Boolean True if two strings are not the same and return Boolean False if two
These operators are mainly used along with if condition to compare two strings where the decision is to be
Code:
string1 = "hello"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
Output:
python string.
• “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in the
string.
• “a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a” is in the
string.
A membership operator is also useful to find whether a specific substring is part of a given string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("Hello" in string1)
Output:
character in python string is inserting double quotes in the string surrounded by double-quotes.
Code:
print(string)
Output:
2. Example of non-allowed double quotes with escape sequence operator:
Code:
print(string)
Output:
along with string, the “%” operator is used along with python string. “%” is prefixed to another character
indicating the type of value we want to insert along with the python string. Please refer to the below table
Operator Description
%c Character
%s String
Code:
name = "india"
age = 19
marks = 20.56
print(string1)
print(string2)
print(string3)
print(string3)
Output:
8.Explain various String built in functions and methods with example?
print("\nConverted String:")
print(text.upper())
print("\nConverted String:")
print(text.lower())
print("\nConverted String:")
print(text.title())
print("\nOriginal String")
print(text)
Output:
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Original String
geeKs For geEkS
a = "demon slayer"
b = "TANJIRO"
print(a+b)
print(a[2])
print(a[2:5])
print(a.replace("demon","kibutsuji muzan"))
print(a.upper())
print(b.lower())
print(a.isupper())
print(a.islower())
print((a+b).swapcase())
print(b.isalpha())
print("-".join(b))
print(a.split())
output:
demon slayerTANJIRO
m
mon
kibutsuji muzan slayer
DEMON SLAYER
tanjiro
False
True
DEMON SLAYERtanjiro
True
T-A-N-J-I-R-O
['demon', 'slayer']
print("Geek" == "Geek")
a= “abd”
b=”good”
print(a==b)
OUTPUT:
True
False
a = "nitesh"
b= "harsh"
c="adithya"
d= "Aryan"
e= "vinyak"
f="adithya"
print(a is b)
print(b is not c)
print(c is f)
print(c is not f)
OUTPUT:
False
True
True
False
10. How to split strings and what function is used to perform that
operation?
If you would have worked on Strings in any programming languages, then you might
know about concatenation (combining the strings) and String split is just the
opposite of it. In order to perform split operations on strings, Python provides us with
a built-in function called split().
Python Split function
Python split() method is used to split the string into chunks, and it accepts one
argument called separator.
Syntax:
variable_name = “String value”
variable_name.split()
Example 1:
my_string = “Welcome to Python”
my_string.split()
Output:
[‘Welcome’, ‘to’, ‘Python’]
Let’s see some examples of splitting the string by passing some arguments.
Example 1:
my_string = “Apple,Orange,Mango”
value = my_string.split(‘,’)
Output:
Before the split, the String is: Apple, Orange, Mango
After split, the String is: [‘Apple’, ‘Orange’, ‘Mango’]
Example 2:
my_string = “Welcome0To0Python”
value = my_string.split(‘0’)
print(“After splitting, the String is: “, value)
Output:
Before splitting, the String is: Welcome0To0Python
After splitting, the String is: [‘Welcome’, ‘To’, ‘Python’]
Example 3:
my_string = “Apple,Orange,Mango”
fruit1,fruit2,fruit3 = my_string.split(‘,’)
Output:
First Fruit is: Apple
Second Fruit is: Orange
Third Fruit is: Mango
a = "HELLO"
print(a[0:4] )
print(a[ :3])
print(a[0: ])
print(a[: -1])
print(a[-1: -5])
OUTPUT:
HELL
HEL
HELLO
HELL
#no output
CREATED BY:
from turtle import*
t = Turtle()
s = Screen()
s.bgcolor("indigo")
t.shape("turtle")
t.color("gold","green")
t.speed(2)
t.forward(-230)
for i in range(4):
t.forward(100)
t.right(90)
t.right(90)
t.forward(200)
t.forward(-100)
t.left(90)
t.forward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(200)
t.left(90)
t.forward(100)
t.forward(-200)
t.forward(50)
t.left(90)
t.forward(200)
t.left(90)
t.forward(50)
t.forward(-100)
done()