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

XI STRINGS NOTES FOR BOOK

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)
34 views

XI STRINGS NOTES FOR BOOK

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/ 8

STRINGS IN PYTHON

Strings are contiguous series of characters enclosed in single or double quotes. Python doesn’t
have any separate data type for characters so they are represented as a single character string.
For eg:
>>> s_name = “Amit” # s_name is a variable storing a string.
>>>s = ‘a’ #String can also be enclosed in single quotes
How to Create Strings in Python?
Creating strings: To create string enclose the character or sequence of character in Single or Double
Quotes like shown below
>>> s_name = “Amit” #String enclosed in double quotes
>>>s = ‘a’ # String enclosed in Single Quotes
We can also use str() function to create string:
N = str () # This function will create an empty string
name = str(1234) # This will create a variable name which store a string “1234”
If we execute the following code:
>>>print(name)
Output will come 1234
TRAVERSING STRINGS IN PYTHON:
Traversing a String: It means accessing all the elements of the string one by one using index value.
St = “PYTHON”

Strings in Python
St[1] = Y St[5] = N St[-1] = N St[-6] = P

Iterating through string using for loop:


Traversing the strings in Python using for loop
Code output
str="Welcome" W
for i in str: e
print(i) l
c
o
m
e
str="Welcome" Welcome
for i in str:
print(i,end='')
str="Welcome" W#e#l#c#o#m#e#
for i in str:
print(i,end='#')
OPERATION OF STRINGS IN PYTHON
Concatenation: It refers to joining two or more strings together and WelcomePython
form a new string.
str1="Welcome"
str2 = "Python" (No space between the two words.)
newstr = str1 + str2
print(newstr)
Replicating: It refers to making multiple copies of the same string. WelcomeWelcomeWelcome
str1="Welcome"
str2 = str1*3 New string with three copies of
print(str2) original str1

Membership Operators :
Membership Operator : OUTPUT
There are two membership operators:
1. ‘in’ operator returns True if a substring is present in main string
2. ‘not in’ operator returns True if a substring is not present in main string.

str1 = “Welcome”
print(‘com’ in str1) True
print(‘W’ in str1) True
print(‘Wel’ not in str1) False

String Comparison :
OUTPUT
We can compare the string using relational/comparison operator like
(>, <, >=, <=, ==, !=)
False
print(“amit” == “Amit”)
True
print(“amit” != “Amit”)
False
print(“blog” > “z”)
String slicing in Python
String Slicing: It means to get a slice from a main string. In simple
words we can say that slicing is to get a piece of substring from the
main string.
Syntax: string-name[start:end:step]
(Here end is excluded)
str1= "Informatics"
print(str1[1:5]) nfor

print(str1[3:9]) ormati

print(str1[-10:-5]) nform

print(str1[:]) Informatics

print(str1[:6]) Inform

print(str1[::2]) Ifrais

print(str1[::-1]) scitamrofnI

Note: Last code is to reverse the string


NOTE: Strings are immutable means that the content of the string cannot be changed
str1 = "Informatics" Traceback (most recent call last):
str1[2]='p'
File "main.py", line 2, in <module>

TypeError: 'str' object does not support item


assignment
We can not change the character in the String
Inbuilt Functions of Strings in Python:
Function
Description Code Output
Name

This function splits


the string into a list str = ” I am Learning Python” [‘I’ , ‘am’ , ‘Learning’ ,
split()
of string on the print(str.split()) ‘Python’ ]
basis of delimiter

This function
str = ” I am Learning Python”
upper() converts the string I AM LEARNING PYTHON
print(str.upper())
into uppercase

This function
converts the str = ” I am Learning Python”
lower() i am learning python
string into print(str.lower())
lowercase

This function
replaces a substring
from the main
str = ” I am Learning Python”
string.
newstr=str.replace
replace() As strings are I am Doing Python
(“Learning”,”Doing”)
immutable
print(newstr)
so this function
creates a new
string

This function
return the index of str = “I am Learning Python”
find() 2
substring in a main print(str.find(‘am’))
string.

This function
str = “I am Learning Python”
len() returns the length 20
print(len(str))
of the string.

This function is str=” I am Learning Python”


used to remove print(len(str)) 25
strip()
leading and strnew=str.strip() 20
trailing print(len(strnew))
Whitespaces
from the string.

This function
counts the number str=”I am Learning Python”
2
count() of occurrences of a print(str.count(‘a’))
3
substring in main print(str.count(‘n’))
string

This function
converts the first
alphabet of the
str=”I am Learning Python”
capitalize() string to upper case I am learning python
print(str.capitalize())
and all other
alphabets in small
case

This function
returns the lowest str=”I am Learning Python”
index() 2
index of substring print(str.index(‘a’))
in a string.

This function
returns True if it’s
made of
str=”I am Learning Python”
alphanumeric
print(str.isalnum()) False (#it contain spaces)
characters
isalnum()
only.
str=”IamLearningPython” True
If there is one
print(str.isalnum())
space in a string,
this function will
return False.

str=”12345678″
This function True(#only digits)
print(str.isdigit())
returns True if all
isdigit() the characters in
the string are digits
str=”12345678A”
otherwise False. False(#contain alphabet)
print(str.isdigit())

This function str=”I am Learning Python” False(#contain upper case


returns True if all print(str.islower()) alphabet)
islower() the characters in
the string are in str=”i am learning python”
lower case print(str.islower()) True

This function str=”I am Learning Python” False(#contain small case)


isupper() returns print(str.isupper())
True if all the
characters in the str=”I AM LEARNING PYTHON”
string are in upper print(str.isupper()) True
case

str=”I am Learning Python” False


print(str.isspace())
This function
returns True if all
str=” “
isspace() the characters in
print(str.isspace()) True (#contain only space)
the string is
whitespace.
str = “”
print(str.isspace()) False

This function
converts the given
string in title str=”i am learning python”
istitle() I Am Learning Python
case(first alphabet print(str.title())
of each word is in
upper case).

This function
converts
str=”I am Learning Python”
swapcase() the lowercase i AM lEARNING pYTHON
print(str.swapcase())
characters to upper
case and vice-versa.

Practice Questions
1. Write a program to count the frequency of a character in a string.
str=input("Enter any String")
ch=input("Enter the character")
print(str.count(ch))

Q2. Write a program to accept a string and return a string having first letter of each word in capital.
str=input("Enter any String")
print(str.title())

Q3. Write a program to accept a string and display the following:


1. Number of uppercase characters
2. Numbers of lowercase characters
3. Total number of alphabets
4. Number of digits
str=input("Enter any String")
u=0
L=0
d=0
l = len(str)
for i in range(l):
if str[i].isupper():
u = u+1
if str[i].islower():
L=L+1
if str[i].isdigit():
d = d+1
print("Total Upper Case Characters are: ", u)
print("Total Lower Case Characters are: ", L)
print("Total Characters are: ", L + u)
print("Total digits are: ", d)

Q4. Write a program to reverse a string.


str=input("Enter any String")
print(str[::-1])
Predict the output of the following codes:
Q.NO CODINGS OUTPUT
1) for i in range(5): 1
print(i) 2
3
4
2) for i in (1,2,3): 1
print(i) 2
3
3) for i in (2,3,4): i
print("i") i
i
4) for i in (4,3,2,1,0): 43210
print(i, end=" ")

5) for i in range(10): Hello 1


if(i%2!=0): Hello 3
print("Hello",i) Hello 5
Hello 7
Hello 9
6) for i in range(10,2,-2): 10 Hello
print(i, "Hello") 8 Hello
6 Hello
4 Hello
7) str = "Python Output based Questions" Python
word=str.split() Output
for i in word: based
print(i) Questions
8) for i in range(7,10): Python Output based
print("Python Output based Questions") Questions Python Output
print("Python Output based Questions") based Questions Python
Output based Questions
Python Output based
Questions
9) for i in range(7,-2,-9): 0
for j in range(i): 1
print(j) 2
3
4
5
6
10) i="9" 9
for k in i:
print(k)
11) for i in range(1,8): 1
print(i) 2
i+=2 3
4
5
6
7
12) for i in range(4,7): Hello
i=i+3 Hello
print("Hello") Hello
13) for i in range(4,7): Hello 7
i=i+3 Hello 8
print("Hello",i) Hello 9
14) i=4 7
while(i<10): 10
i=i+3
print(i)
15) for i in range(20): 0
if i//4==0: 1
print(i) 2
3
16) x=1234 123
while x%10: 12
x=x//10 1
print(x) 0
17) for i in 1,2,3: 1
print(i*i) 4
9
18) for i in 2,4,6: HH
print("H"*i) HHHH
HHHHHH
19) for i in 123: TypeError
print(i)
20) for i in [10,20,30]: Hello 10
print("Hello",i) Hello 20
Hello 30
21) x=2 2
for i in range(x**2,x,-1): 2
print(x)
22) s=0 0
for i in range(5): 1
s=s+i 3
print(s) 6
10
23) x=5 25
64
while(x<15): 121
print(x**2) 196
x+=3

24) a=7 12
b=5 13

while(a<9):
print(a+b)
a+=1
25) b=5 H
H
while(b<9): H
print("H") H
b+=1
26) x=15 Hello

while(x==15):
print("Hello")
x=x-3
27) x = "123" a
for i in x: a
print("a") a
28) i=2 3
for x in range(i): 3
i+=1 4
print(i) 4
print(i)
29) i=2 1
2
for x in range(i): 2
x+=1
print(x)
print(x)

30) i=2 1
x
for x in range(i): 2
x+=1 x
print(x)
print("x")
31) a=7 Error
for i in 7:
print(a)
32) a = "AMIT" AMIT
for i in range(len(a)): AMIT
print(a) AMIT
AMIT
33) for i in range(0,2,-1): No output
print("Hello")

You might also like