0% found this document useful (0 votes)
35 views17 pages

Wa0019.

The document discusses strings in Python. It explains what strings are, how to define and access characters in strings, that strings are immutable, various string operations like concatenation and slicing, built-in string methods, and provides examples of using functions to manipulate strings.

Uploaded by

skanupbossgaming
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)
35 views17 pages

Wa0019.

The document discusses strings in Python. It explains what strings are, how to define and access characters in strings, that strings are immutable, various string operations like concatenation and slicing, built-in string methods, and provides examples of using functions to manipulate strings.

Uploaded by

skanupbossgaming
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/ 17

DAV SDPS PUBLIC SCHOOL, BHADRAK

Strings in Python
Strings
A string is a group of one or more UNICODE characters in sequence. A letter,
number, space, or any other sign may be used as the character in this
situation. One or more characters can be enclosed in a single, double, or triple
quote to produce a string.

Example –

>>> str1 = ‘Hello World!’


>>> str2 = “Hello World!”
>>> str3 = “””Hello World!”””
>>> str4 = ”’Hello World!”

Note – Python accepts single (‘), double (“), triple (”’) or triple(“””) quotes to
denote string literals. Single quoted strings and double quoted strings are
equal. Triple quotes are used for contain special characters like TAB, or
NEWLINES.

Accessing Characters in a String

A method known as indexing can be used to retrieve each individual character


in a string. The character to be retrieved in the string is specified by the index,
which is enclosed in square brackets ([ ]). The string has an index of 0 for the
first character (counted from the left) and n-1 for the last character, where n is
the string’s length. We receive an IndexError if we provide an index value
outside of this range. A number must make up the index (positive, zero or
negative).
String is Immutable

A string is an immutable data type. It means that the contents of the string
cannot be changed after it has been created. An attempt to do this would lead
to an error.

>>> str1 = “Hello World!”


#if we try to replace character ‘e’ with ‘a’
>>> str1[1] = ‘a’
TypeError: ‘str’ object does not support item assignment

String Operations

A string is a group of letters and numbers. Concatenation, repetition,


membership, and slicing are just a few of the operations Python supports on
the string data type. The following subsections provide explanations of these
procedures along with pertinent examples.

Concatenation

To concatenate means to join. Python allows us to join two strings using


concatenation operator plus which is denoted by symbol +.

>>> str1 = ‘Hello’


>>> str2 = ‘World!’
>>> str1 + str2

Output:
Hello World!
Repetition

Python allows us to repeat the given string using repetition operator which is
denoted by symbol *.

>>> str1 = ‘Hello’


>>> str1 * 2

Output:
>>> str1 * 5
‘HelloHelloHelloHelloHello’

Membership

Python has two membership operators ‘in’ and ‘not in’. The ‘in’ operator takes
two strings and returns True if the first string appears as a substring in the
second string, otherwise it returns False.

In

>>> str1 = ‘Hello World!’


>>> ‘W’ in str1
True
>>> ‘Wor’ in str1
True
>>> ‘My’ in str1
False

Not In

>>> str1 = ‘Hello World!’


>>> ‘My’ not in str1
True
>>> ‘Hello’ not in str1
False

Slicing

In Python, to access some part of a string or substring, we use a method


called slicing. This can be done by specifying an index range. Given a string
str1, the slice operation str1[n:m].

>>> str1 = ‘Hello World!’


>>> str1[1:5]
‘ello’
>>> str1[7:10]
‘orl’
>>> str1[3:20]
‘lo World!’
>>> str1[7:2]

Traversing a String

We can access each character of a string or traverse a string using for loop
and while loop.

String Traversal Using for Loop:

>>> str1 = ‘Hello World!’


>>> for ch in str1:
print(ch,end = ”)
Hello World!

In the above code, the loop starts from the first character of the string str1
and automatically ends when the last character is accessed.

String Traversal Using while Loop:

>>> str1 = ‘Hello World!’


>>> index = 0>>> while index < len(str1):
print(str1[index],end = ”)
index += 1
Hello World!

Here while loop runs till the condition index < len(str) is True, where index
varies from 0 to len(str1) -1.

String Methods and Built-in Functions

There are numerous built-in functions in Python that let us operate with
strings. a few of the most popular built-in functions for manipulating strings.

len()

Returns the length of the given string

>>> str1 = ‘Hello World!’


>>> len(str1)
12
title()

Returns the string with first letter of every word in the string in uppercase and
rest in lowercase

>>> str1 = ‘hello WORLD!’


>>> str1.title()
‘Hello World!’

lower()

Returns the string with all uppercase letters converted to lowercase

>>> str1 = ‘hello WORLD!’


>>> str1.lower()
‘hello world!’

upper()

Returns the string with all lowercase letters converted to uppercase

>>> str1 = ‘hello WORLD!’


>>> str1.upper()
‘HELLO WORLD!’

count(str, start, end)

Returns number of times substring str occurs in the given string. If we do not
give start index and end index then searching starts from index 0 and ends at
length of the string.

>>> str1 = ‘Hello World! Hello


Hello’
>>> str1.count(‘Hello’,12,25)
2
>>> str1.count(‘Hello’)
3

find(str, start, end)

Returns the first occurrence of index of substring str occurring in the given
string. If we do not give start and end then searching starts from index 0 and
ends at length of the string. If the substring is not present in the given string,
then the function returns -1
>>> str1 = ‘Hello World! Hello Hello’
>>> str1.find(‘Hello’,10,20)
13
>>> str1.find(‘Hello’,15,25)
19
>>> str1.find(‘Hello’)
0
>>> str1.find(‘Hee’)
-1

index(str, start, end)

Same as find() but raises an exception if the substring is not present in the
given string

>>> str1 = ‘Hello World! Hello


Hello’
>>> str1.index(‘Hello’)
0
>>> str1.index(‘Hee’)
ValueError: substring not found

endswith()

Returns True if the given string ends with the supplied substring otherwise
returns False

>>> str1 = ‘Hello World!’


>>> str1.endswith(‘World!’)
True
>>> str1.endswith(‘!’)
True
>>> str1.endswith(‘lde’)
False

startswith()

Returns True if the given string starts with the supplied substring otherwise
returns False

>>> str1 = ‘Hello World!’


>>> str1.startswith(‘He’)
True
>>> str1.startswith(‘Hee’)
False
isalnum()

Returns True if characters of the given string are either alphabets or numeric.
If whitespace or special symbols are part of the given string or the string is
empty it returns False

>>> str1 = ‘HelloWorld’


>>> str1.isalnum()
True
>>> str1 = ‘HelloWorld2’
>>> str1.isalnum()
True
>>> str1 = ‘HelloWorld!!’
>>> str1.isalnum()
False

islower()

Returns True if the string is non-empty and has all lowercase alphabets, or has
at least one character as lowercase alphabet and rest are non-alphabet
characters

>>> str1 = ‘hello world!’


>>> str1.islower()
True
>>> str1 = ‘hello 1234’
>>> str1.islower()
True
>>> str1 = ‘hello ??’
>>> str1.islower()
True
>>> str1 = ‘1234’
>>> str1.islower()
False
>>> str1 = ‘Hello World!’
>>> str1.islower()
False

isupper()

Returns True if the string is non-empty and has all uppercase alphabets, or
has at least one character as uppercase character and rest are non-alphabet
characters

>>> str1 = ‘HELLO WORLD!’


>>> str1.isupper()
True
>>> str1 = ‘HELLO 1234’
>>> str1.isupper()
True
>>> str1 = ‘HELLO ??’
>>> str1.isupper()
True
>>> str1 = ‘1234’
>>> str1.isupper()
False
>>> str1 = ‘Hello World!’
>>> str1.isupper()
False

isspace()

Returns True if the string is non-empty and all characters are white spaces
(blank, tab, newline, carriage return)

>>> str1 = ‘ \n \t \r’


>>> str1.isspace()
True
>>> str1 = ‘Hello \n’
>>> str1.isspace()
False

istitle()

Returns True if the string is non-empty and title case, i.e., the first letter of
every word in the string in uppercase and rest in lowercase

>>> str1 = ‘Hello World!’


>>> str1.istitle()
True
>>> str1 = ‘hello World!’
>>> str1.istitle()
False

lstrip()

Returns the string after removing the spaces only on the left of the string

>>> str1 = ‘ Hello World!’


>>> str1.lstrip()
‘Hello World!

Strings in Python Class 11 Notes

rstrip()

Returns the string after removing the spaces only on the right of the string

>>> str1 = ‘ Hello World!’


>>> str1.rstrip()
‘ Hello World!’

strip()

Returns the string after removing the spaces both on the left and the right of
the string

>>> str1 = ‘ Hello World!’


>>> str1.strip()
‘Hello World!’

replace(oldstr, newstr)

Replaces all occurrences of old string with the new string

>>> str1 = ‘Hello World!’


>>> str1.replace(‘o’,’*’)
‘Hell* W*rld!’
>>> str1 = ‘Hello World!’
>>> str1.replace(‘World’,’Country’)
‘Hello Country!’
>>> str1 = ‘Hello World! Hello’
>>> str1.replace(‘Hello’,’Bye’)
‘Bye World! Bye’

join()

Returns a string in which the characters in the string have been joined by a
separator

>>> str1 = (‘HelloWorld!’)


>>> str2 = ‘-‘ #separator
>>> str2.join(str1)
‘H-e-l-l-o-W-o-r-l-d-!’
partition()

Partitions the given string at the first occurrence of the substring (separator)
and returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator
If the separator is not found in the string, it returns the whole string itself and
two empty strings

>>> str1 = ‘India is a Great Country’


>>> str1.partition(‘is’)
(‘India ‘, ‘is’, ‘ a GreatCountry’)
>>> str1.partition(‘are’)
(‘India is a Great Country’,’ ‘,”)

split()

Returns a list of words delimited by the specified substring. If no delimiter is


given then words are separated by space.

>>> str1 = ‘India is a Great Country’


>>> str1.split()
[‘India’,’is’,’a’,’Great’, ‘Country’]
>>> str1 = ‘India is a Great Country’
>>> str1.split(‘a’)
[‘Indi’, ‘ is ‘, ‘ Gre’, ‘t Country’]

Handling Strings

In this section, we’ll discover how to use user-defined functions in Python to


manipulate strings in various ways.

Q. Write a program with a user defined function to count the number of times
a character (passed as argument) occurs in the given string.

#Program
#Function to count the number of times a character occurs in a
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input(“Enter a string: “)
ch = input(“Enter the character to be searched: “)
count = charCount(ch,st)
print(“Number of times character”,ch,”occurs in the string is:”,count)

Output:
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3

Strings in Python Class 11 Notes

Q. Write a program with a user defined function with string as a parameter


which replaces all vowels in the string with ‘*’.

#Program
#Function to replace all vowels in the string with ‘*’
def replaceVowel(st):
newstr = ”
for character in st:
if character in ‘aeiouAEIOU’:
newstr += ‘*’
else:
newstr += character
return newstr
st = input(“Enter a String: “)
st1 = replaceVowel(st)
print(“The original String is:”,st)
print(“The modified String is:”,st1)

Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld

Q. Write a program to input a string from the user and print it in the reverse
order without creating a new string.

#Program
#Program to display string in reverse order
st = input(“Enter a string: “)
for i in range(-1,-len(st)-1,-1):
print(st[i],end=”)

Output:
Enter a string: Hello World
dlroW olleH

Q. Write a program which reverses a string passed as parameter and stores


the reversed string in a new string. Use a user defined function for reversing
the string.

#Program
#Function to reverse a string
def reverseString(st):
newstr = ” #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
#end of function
st = input(“Enter a String: “)
st1 = reverseString(st)
print(“The original String is:”,st)
print(“The reversed String is:”,st1)

Output:
Enter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleH

Q. Write a program using a user defined function to check if a string is a


palindrome or not. (A string is called palindrome if it reads same backwards
as forward. For example, Kanak is a palindrome.)

#Program
#Function to check if a string is palindrome or not
def checkPalin(st):
i=0
j = len(st) – 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True
#end of function
st = input(“Enter a String: “)
result = checkPalin(st)
if result == True:
print(“The given string”,st,”is a palindrome”)
else:
print(“The given string”,st,”is not a palindrome”)

Output 1:
Enter a String: kanak
The given string kanak is a palindrome
Output 2:
Enter a String: computer
The given string computer is not a palindrome

Questions and Answers


1. Consider the following string mySubject:
mySubject = “Computer Science”
What will be the output of the following string operations :
i. print(mySubject[0:len(mySubject)])
Answer – Computer Science

ii. print(mySubject[-7:-1])
Answer – Scienc

iii. print(mySubject[::2])
Answer – Cmue cec

iv. print(mySubject[len(mySubject)-1])
Answer – e

v. print(2*mySubject)
Answer – Computer ScienceComputer Science

vi. print(mySubject[::-2])
Answer – eniSrtpo

vii. print(mySubject[:3] + mySubject[3:])


Answer – Computer Science

viii. print(mySubject.swapcase())
Answer – cOMPUTER sCIENCE

ix. print(mySubject.startswith(‘Comp’))
Answer – True

x. print(mySubject.isalpha())
Answer – False
2. Consider the following string myAddress:
myAddress = “WZ-1,New Ganga Nagar,New Delhi”

What will be the output of following string operations :

i. print(myAddress.lower())
Answer – wz-1,new ganga nagar,new delhi

ii. print(myAddress.upper())
Answer – WZ-1,NEW GANGA NAGAR,NEW DELHI

iii. print(myAddress.count(‘New’))
Answer – 2

iv. print(myAddress.find(‘New’))
Answer – 5

v. print(myAddress.rfind(‘New’))
Answer – 21

vi. print(myAddress.split(‘,’))
Answer – [‘WZ-1’, ‘New Ganga Nagar’, ‘New Delhi’]

vii. print(myAddress.split(‘ ‘))


Answer – [‘WZ-1,New’, ‘Ganga’, ‘Nagar,New’, ‘Delhi’]

viii. print(myAddress.replace(‘New’,’Old’))
Answer – WZ-1,Old Ganga Nagar,Old Delhi

ix. print(myAddress.partition(‘,’))
Answer – (‘WZ-1’, ‘,’, ‘New Ganga Nagar,New Delhi’)

x. print(myAddress.index(‘Agra’))
Answer – ValueError: substring not found

3. Write a program to input line(s) of text from the user until enter is pressed.
Count the total number of characters in the text (including white
spaces),total number of alphabets, total number of digits, total number of
special symbols and total number of words in the given text. (Assume that
each word is separated by one space).
Answer –
str = input(“Enter your text : “)
Alpha = 0
Digit = 0
Special = 0
words = 0
for ch in str:
if ch.isalpha():
Alpha += 1
elif ch.isdigit():
Digit += 1
else:
Special += 1

for ch1 in str:


if ch1.isspace():
words += 1
print(“Alphabets: “,Alpha)
print(“Digits: “,Digit)
print(“Special Characters: “,Special)
print(“Words in the Input :”,(words + 1))

Output
Enter your text : Hello how are you
Alphabets: 14
Digits: 0
Special Characters: 3
Words in the Input : 4

4. Write a user defined function to convert a string with more than one word
into title case string where string is passed as parameter. (Title case means
that the first letter of each word is capitalised)
Answer –
def convertToTitle(string):
titleString = string.title();
print(titleString)

str = input(“Type your Text : “)


Space = 0
for b in str:
if b.isspace():
Space += 1

if(str.istitle()):
print(“The String is already in title case”)
elif(Space > 0):
convertToTitle(str)
else:
print(“One word String”)
Output
Type your Text : Welcome to my school
Welcome To My School

5. Write a function deleteChar() which takes two parameters one is a string


and other is a character. The function should create a new string after
deleting all occurrences of the character from the string and return the new
string.
Answer –
def deleteChar(string,char):
str = “”
for ch in string:
if ch != char:
str+=ch
return str

string = input(“Enter a string: “)


char = (input(“Enter a character: “))[0]
print(deleteChar(string,char))

6. Input a string having some digits. Write a function to return the sum of
digits present in this string.
Answer –
def myfunction(string):
sum = 0
for a in string:
if(a.isdigit()):
sum += int(a)
return sum

str = input(“Enter any string with digits : “)


result = myfunction(str)
print(“The sum of digits in the string : “,result)

Output
Enter any string with digits : Welcome 225
The sum of digits in the string : 9

7. Write a function that takes a sentence as an input parameter where each


word in the sentence is separated by a space. The function should replace
each blank with a hyphen and then return the modified sentence.
Answer –
def myfunction():
string = input(“Enter a sentence: “)
str = string.replace(” “,”-“)
print(str)

myfunction()

Output
Enter a sentence: Welcome to my school
Welcome-to-my-school

You might also like