Python Revision Tour – II : String, Lists, Tuples, Dictionary – Notes

Class 12 Computer Science Python Revision Tour – II Notes


String/Text Handling in Python


What is a String?

Python strings are characters enclosed in quotes of any type – single quotation marks, double quotation marks, triple quotation marks.

An Empty string is a string that has 0 characters, i.e. ‘ ’ , “ ”, “““ ”””

S = ‘Anjeev Singh Academy’ ,    

T =  “Singh@123”

Example:-

Mline = ‘‘‘Anjeev Singh Academy
is the best free online academy
on YouTube ’’’

Characteristics of String

Python strings is an immutable data type, i.e. not allowed to change in place. S[0] =‘R’ not allowed

Strings are sequences of characters, where each character has a unique index number.

The indexes of strings begin from 0 to length-1, in forward direction and  -1, -2, -3, …. , -length in backward direction.

String Traversal

Traversing a String or Text means accessing all characters of the string, character by character, through its index position.


Program – 1 : Python program to traverse a string forward using Loop.

Name = "mycstutorial.in"
for ch in Name:
    print(ch, end= " ")

Output:

m y c s t u t o r i a l . i n


Program 2 – Python program to traverse a string forward using indexing.

Name = "mycstutorial.in"
for index in range(len(Name)):
    print(Name[index],  end= " ")

Output:

m y c s t u t o r i a l . i n



Program 3 – Python program to traverse a string backward using indexing.

Name = "mycstutorial.in"
for index in range(len(Name)-1, -1, -1):
    print(Name[index],  end= " ")

Output:

n i . l a i r o t u t s c y m


Program 4 – Python program to search a character in the string using indexing.

Name = "mycstutorial.in"
ch = input("Enter a character to search : ")

Found = False

for index in range(len(Name)-1, -1, -1):
    if Name[index] == ch:
        Found = True

if Found :
    print(ch, "found in", Name)
else:
    print(ch, "not found")

Output:

Enter a character to search : o
o found in mycstutorial.in

Enter a character to search : x
x not found



Program 5 – Python program to count occurrences of a character in the string using indexing.

Name = "abc abc xyz abc pqr"
ch = input("Enter a character to count : ")

count = 0

for index in range(len(Name)-1, -1, -1):
    if Name[index] == ch:
        count += 1

print(ch, "found ", count, "time(s)")

Output:

Enter a character to search : a
a found 3 time(s)

Enter a character to search : p
p found 1 time(s)

Enter a character to search : t
t found 0 time(s)

String Operators

Strings can be manipulated by using string operators. Python supports the following types of string operators.

OperatorNameDescription
+ConcatenationAdd two strings i.e. concatenate two strings. e.g.      S = “Hello” + “Shyam”
*Replication  / RepetitionReplicate the string upto n times.
in / not inMembershipTo check given character exists in the string or not.
[index]Element AccessorExtract the character from the given index position.
[ : ]Slicing [start:end:step]Extracts the characters from the given range i.e start to stop
==, !=, < , > , <=, >=Relational / Comparison OperatorThese relational operators can do comparison between strings, based on character by character  comparison rules for Unicode or Ordinal Value

String Slicing

Slice means ‘a part of’.  In Python, a string slice refers to a part of the string containing some contiguous characters from the string.

Syntax:

string[start : end : step]

  • where start and end are integers with legal indices.
  • will return the characters falling between indices start and end. i.e. start, start+1, start+2,…, till end-1.
  • By default value of step is 1. It is an optional argument.

Example: –

SliceOutput, if str = “Hello Anjeev
str[ 2 : ]‘llo Anjeev”
str[ : 5]“Hello”
str[4 : 8]“o Anj”
str[ : : 2]“HloAje”
str[ : : -1]“veejnA olleH”
str[-6 : -2 ]“Anje”

String Functions

Syntax to call the method – string.methodName( )

MethodsDescription
isalpha()Returns True, if the string contains only letters, otherwise returns False.
>>>”abc”.isalpha()
True
>>>”1abc”.isalpha()
False
isalnum()Returns True, if the string contains alphanumeric (i.e. alphabets or number or both), otherwise returns False.
>>>”abc”.isalnum()
True
>>>”123″.isalnum()
True
>>>”a123″.isalnum()
True
>>>”@#2″.isalnum()
False
>>>”@#12ab”.isalnum()
False
isdigit( )Return True, if the string contains only digits, otherwise returns False.
>>>”123″.isdigit()
True
>>>”abc123″.isdigit()
False
isspace( )Returns True, if the string contains only spaces, otherwise returns False.

>>>” “.isspace()
True
>>>”a “.isspace()
False
>>>” a”.isspace()
False
islower( )Returns True if the string contains all lowercase characters, otherwise returns False.

>>>”mycstutorial.in”.islower()
True
>>>”MYCSTUTORIAL.IN”.islower()
False
isupper()Returns True, if the string contains all uppercase characters, otherwise returns False.

>>>”MYCSTUTORIAL.IN”.isupper()
True
>>>”mycstutorial.in”.isupper()
False
istitle( )Returns True, if string is properly “TitleCasedString”, otherwise returns False.

>>>”Anjeev Singh Academy”.istitle()
True
>>>”Anjeev singh academy”.istitle()
False
>>>”Anjeevsinghacademy”.istitle()
True
startswith()Returns True, if string is starts with the given substring.
>>> name=”tanmay singh”
>>> name.startswith(‘tan’)
True
>>> name.startswith(‘tannu’)
False
endswith()Returns Ture, if string is ends with the given substring.
>>> name=”tanmay singh”
>>> name.endswith(‘singh’)
True
>>> name.endswith(‘nh’)
False
MethodsDescription
len(string )Returns the length of string, i.e. number of characters.

>>> name=”tanmay singh”
>>> len(name)
12
capitalize( )Returns a copy of string with its first character capitalized.

>>> name=”tanmay singh”
>>> name.capitalize()
‘Tanmay singh’
lower( )Returns a copy of string converted to lowercase.

>>> name=”TANMAY SINGH”
>>> name.lower()
‘tanmay singh’
upper( )Returns a copy of string converted to uppercase.

>>> name=”tanmay singh”
>>> name.upper()
‘TANMAY SINGH’
title()Returns a copy of string converted to title case.
>>> name=”tanmay singh”
>>> name.title()
‘Tanmay Singh’
swapcase()Converts and returns all uppercase characters to lowercase and vice-versa.
>>> name=”Tanmay Singh”
>>> name.swapcase()
‘tANMAY sINGH’
index(char)Search and returns the first occurence of given character or substring.
>>> name=”tanmay singh”
>>> name.index(‘y’)
5
ord(char)Returns the ordinal value (ASCII) of given character.
>>> ord(‘a’)
97
>>> ord(‘A’)
65
>>> ord(‘#’)
35
chr(num)Returns character represented by inputted ASCII number.

>>> chr(35)
‘#’
>>> chr(65)
‘A’
>>> chr(97)
‘a’
MethodsDescription
count()Returns the number of times a specified value occurs in a string.
>>> name=”tanmay singh”
>>> name.count(‘a’)
2
lstrip() / lstrip(char)Returns a copy of the string with leading characters removed. By default removed space.
>>> data = ‘ hello ‘
>>> data.lstrip()
‘hello ‘
>>> mesg = ‘aaaRAMaaa’
>>> mesg.lstrip(‘a’)
‘RAMaaa’
rstrip()/ rstrip(char)Returns a copy of the string with trailing characters removed. By default removed space.

>>> data = ‘ hello ‘
>>> data.rstrip()
‘ hello’
>>> mesg = ‘aaaRAMaaa’
>>> mesg.rstrip(‘a’)
‘aaaRAM’
strip()Returns a copy of the string with leading and trailing characters removed.
>>> data = ‘ hello ‘
>>> data.strip()
‘hello’
>>> mesg = ‘aaaRAMaaa’
>>> mesg.strip(‘a’)
‘RAM’
split()Splits the string at the specified separator, and returns a list.
>>> name=”tanmay singh”
>>> name.split(‘n’)
[‘ta’, ‘may si’, ‘gh’]

>>> message = “Hello dear welcome to mycstutorial.in”
>>> message.split()
[‘Hello’, ‘dear’, ‘welcome’, ‘to’, ‘mycstutorial.in’]
partition()Splits the string at the specified separator, and returns a tuple.
>>> name=”tanmay singh”
>>> name.partition(‘n’)
(‘ta’, ‘n’, ‘may singh’)

>>> message = “Hello dear welcome to mycstutorial.in”
>>> message.partition(‘ ‘)
(‘Hello’, ‘ ‘, ‘dear welcome to mycstutorial.in’)
join()Returns a string in which the string elements have been joined by a string separator.  Eg. ‘-’.join(‘anjeev” => ‘a-n-j-e-e-v’

>>> name=”tanmay singh”
>>> ‘#’.join(name)
‘t#a#n#m#a#y# #s#i#n#g#h’

>>> “–He–“.join(name)
‘t–He–a–He–n–He–m–He–a–He–y–He– –He–s–He–i–He–n–He–g–He–h’

Class 12 Computer Science Python Revision Tour – II Notes


Leave a Comment

You cannot copy content of this page

Scroll to Top