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

Module 3 Strings Solutions

Strings are sequences of characters that can be represented and manipulated in Python. Strings can be created by enclosing characters in single quotes, double quotes, or triple quotes and assigning to a variable. The type of all string variables is 'str'. Individual characters in a string can be accessed using indexing with integers and slices of a string can be accessed using a colon. Strings are immutable, so their characters cannot be modified, only replaced. The len() function returns the length or number of characters in a string.

Uploaded by

yashwanth
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)
131 views

Module 3 Strings Solutions

Strings are sequences of characters that can be represented and manipulated in Python. Strings can be created by enclosing characters in single quotes, double quotes, or triple quotes and assigning to a variable. The type of all string variables is 'str'. Individual characters in a string can be accessed using indexing with integers and slices of a string can be accessed using a colon. Strings are immutable, so their characters cannot be modified, only replaced. The len() function returns the length or number of characters in a string.

Uploaded by

yashwanth
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/ 26

Module 3

STRINGS

1. What is String? How do u create a string in Python?

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.

How to create a string and assign it to a variable

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.

>>> single_quote_character = 'a'


>>> print(single_quote_character)
a
>>> print(type(single_quote_character)) # check the type of
the variable.
<class 'str'>

Similarly, you can assign a single character to a


variable double_quote_character. Note that the string is a single character but
it is “enclosed” by double quotes.

>>> double_quote_character = "b"


>>> print(double_quote_character)
b
>>> print(type(double_quote_character))
<class 'str'>

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.

>>> double_quote_multiple_characters = "aeiou"


>>> single_quote_multiple_characters = 'aeiou'
>>> print(type(double_quote_multiple_characters),
type(single_quote_multiple_characters))
<class 'str'> <class 'str'>

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.

>>> triple_quote_example = """this is a sentence written in


triple quotes"""
>>> print(type(triple_quote_example))
<class 'str'>

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.

2.How to access characters of a string?

Accessing characters in Python


In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed
to be passed as an index, float or other types that will cause a TypeError.
• Python3

# Python Program to Access

# characters of String

String1 = "GeeksForGeeks"

print("Initial String: ")

print(String1)

# Printing First character

print("\nFirst character of String is: ")

print(String1[0])

# Printing Last character

print("\nLast character of String is: ")

print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s
String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String is
done by using a Slicing operator (colon).

• Python3

# Python Program to

# demonstrate String slicing

# Creating a String

String1 = "GeeksForGeeks"

print("Initial String: ")

print(String1)

# Printing 3rd to 12th character

print("\nSlicing characters from 3-12: ")

print(String1[3:12])

# Printing characters between

# 3rd and 2nd last character

print("\nSlicing characters between " +

"3rd and 2nd last character: ")

print(String1[3:-2])

Output:
Initial String:
GeeksForGeeks

Slicing characters from 3-12:


ksForGeek

Slicing characters between 3rd and 2nd last character:


ksForGee

2. Illustrate negative indexing in list with an example.

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

3.Describe list slicing with examples.

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

Lst = [50, 70, 30, 20, 90, 10, 50]

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

NO,String is an example of an immutable type. A String object always


represents the same string.

String cannot be modified or changed once created but it can only be


replaced or deleted .we cannot change the character in string we
cannot append or change the middle character of string

a = "messi"
for i in a:
if i =='m':
m='b'
print(a)
OUTPUT:
messi

so we can see that we cannot modify or change the character of string

5.What is len function and explain how it is used on strings with an


example.

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.

Example 1: How find the length of the given string?


# testing len()
str1 = "Welcome to Guru99 Python Tutorials"
print("The length of the string is :", len(str1))
Output:

The length of the string is : 35

6.Explain about string slicing with examples

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

7. What are the operators that are used in string functions?

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

string are as below:


• Assignment operator: “=.”

• Concatenate operator: “+.”

• String repetition operator: “*.”

• String slicing operator: “[]”

• String comparison operator: “==” & “!=”

• Membership operator: “in” & “not in”

• Escape sequence operator: “\.”

• String formatting operator: “%” & “{}”

Example #1 – Assignment Operator “=.”


Python string can be assigned to any variable with an assignment operator “= “. Python string can be

defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name = “string” assigns

“string” to variable var_name.

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"

string2 = "world "

string_combined = string1+string2

print(string_combined)

Output:

Example #3 – String Repetition Operator “*.”


The same string can be repeated in python by n times using string*n, as explained in the below example.

Code:

string1 = "helloworld "

print(string1*2)

print(string1*3)
print(string1*4)

print(string1*5)

Output:

Example #4 – String slicing operator “[]”


Characters from a specific index of the string can be accessed with the string[index] operator. The index is

interpreted as a positive index starting from 0 from the left side and a negative index starting from -1 from

the right side.

String H E L L O W O R L D

Positive index 0 1 2 3 4 5 6 7 8 9

Negative index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

• string[a]: Returns a character from a positive index a of the string from the left side as displayed in

the index graph above.

• string[-a]: Returns a character from a negative index a of the string from the right side as displayed

in the index graph above.

• 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

displayed in the index graph above.

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

• string[::-1]: Returns a string with reverse order.

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

strings are not the same.

• “!=” operator returns Boolean True if two strings are not the same and return Boolean False if two

strings are the same.

These operators are mainly used along with if condition to compare two strings where the decision is to be

taken based on string comparison.

Code:

string1 = "hello"

string2 = "hello, world"

string3 = "hello, world"

string4 = "world"

print(string1==string4)

print(string2==string3)
print(string1!=string4)

print(string2!=string3)

Output:

Example #6 – Membership Operator “in” & “not in”


Membership operator is used to searching whether the specific character is part/member of a given input

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("t" not in string1)


print("hello" in string1)

print("Hello" in string1)

print("hello" not in string1)

Output:

Example #7 – Escape Sequence Operator “\.”


To insert a non-allowed character in the given input string, an escape character is used. An escape character

is a “\” or “backslash” operator followed by a non-allowed character. An example of a non-allowed

character in python string is inserting double quotes in the string surrounded by double-quotes.

1. Example of non-allowed double quotes in python string:

Code:

string = "Hello world I am from "India""

print(string)

Output:
2. Example of non-allowed double quotes with escape sequence operator:

Code:

string = "Hello world I am from \"India\""

print(string)

Output:

Example #8 – String Formatting Operator “%.”


String formatting operator is used to format a string as per requirement. To insert another type of variable

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

for some of the commonly used different string formatting specifiers:

Operator Description

%d Signed decimal integer

%u unsigned decimal integer

%c Character
%s String

%f Floating-point real number

Code:

name = "india"

age = 19

marks = 20.56

string1 = 'Hey %s' % (name)

print(string1)

string2 = 'my age is %d' % (age)

print(string2)

string3= 'Hey %s, my age is %d' % (name, age)

print(string3)

string3= 'Hey %s, my subject mark is %f' % (name, marks)

print(string3)

Output:
8.Explain various String built in functions and methods with example?

Case Changing of Strings


The below functions are used to change the case of the strings.
• lower(): Converts all uppercase characters in a string into lowercase
• upper(): Converts all lowercase characters in a string into uppercase
• title(): Convert string to title case
Example: Changing the case of Python Strings.
• Python3

# Python3 program to show the

# working of upper() function

text = 'geeKs For geEkS'

# upper() function to convert

# string to upper case

print("\nConverted String:")

print(text.upper())

# lower() function to convert

# string to lower case

print("\nConverted String:")

print(text.lower())

# converts the first character to

# upper case and rest to lower case

print("\nConverted String:")
print(text.title())

# original string never changes

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']

#Explain the above function used on strings in own words

9. Explain string comparison with an example.

Method 1: Using Relational Operators


The relational operators compare the Unicode values of the characters of the
strings from the zeroth index till the end of the string. It then returns a boolean
value according to the operator used.
Example:
“Geek” == “Geek” will return True as the Unicode of all the characters are equal

print("Geek" == "Geek")
a= “abd”
b=”good”
print(a==b)

OUTPUT:
True
False

Method 2: Using is and is not


The == operator compares the values of both the operands and checks for value
equality. Whereas is operator checks whether both the operands refer to the same
object or not. The same is the case for != and is not.
Let us understand this with an example:

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?

What is String Split?


As the name itself explains String split means splitting or breaking the given String
into smaller pieces.

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.

A separator can be any character or a symbol. If no separators are defined, then it


will split the given string and whitespace will be used by default.

Syntax:
variable_name = “String value”

variable_name.split()

Example 1:
my_string = “Welcome to Python”

my_string.split()

Output:
[‘Welcome’, ‘to’, ‘Python’]

How to Split a String in Python?


In the above example, we have used the split() function to split the string without
any arguments.

Let’s see some examples of splitting the string by passing some arguments.

Example 1:
my_string = “Apple,Orange,Mango”

print(“Before splitting, the String is: “, my_string)

value = my_string.split(‘,’)

print(“After splitting, the String is: “, value)

Output:
Before the split, the String is: Apple, Orange, Mango
After split, the String is: [‘Apple’, ‘Orange’, ‘Mango’]

Example 2:
my_string = “Welcome0To0Python”

print(“Before splitting, the String is: “, my_string)

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(‘,’)

print(“First Fruit is: “, fruit1)

print(“Second Fruit is: “, fruit2)

print(“Third Fruit is: “, fruit3)

Output:
First Fruit is: Apple
Second Fruit is: Orange
Third Fruit is: Mango

11.Write a python program to check whether a given string is palindrome


or not.

refer to module 2 answers

12. Discuss various methods used in python


#explain all method in detail with example

13. Explain the different string operation in detail with example.

Refer to question no. 7

15.Discuss the output of the following code.


a=”HELLO”
Print(a[0:4] )
Print(a[ :3])
Print(a[0: ])
Print(a[: -1])
Print(a[-1: -5])

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

Run the code in downloaded python complier or run on online complier


Which supports turtle, link for online complier :
https://pythonandturtle.com/turtle
- ADITYA
M Section

You might also like