0% found this document useful (0 votes)
0 views14 pages

Chapter - 5 Python Collective String

The document provides an overview of strings in Python, including their definition, comparison methods, and various built-in functions and operators for string manipulation. It covers string creation, updating, special operators, and methods for string analysis such as counting vowels and consonants. Additionally, it includes example code snippets demonstrating how to use these features effectively.

Uploaded by

nakul18209
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)
0 views14 pages

Chapter - 5 Python Collective String

The document provides an overview of strings in Python, including their definition, comparison methods, and various built-in functions and operators for string manipulation. It covers string creation, updating, special operators, and methods for string analysis such as counting vowels and consonants. Additionally, it includes example code snippets demonstrating how to use these features effectively.

Uploaded by

nakul18209
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/ 14

Python Collectives

String, string, tuple and dictionary


-Nirali Purohit
String:
String is a sequence of characters, which is enclosed between either single (' ') or double quotes
(" "), python treats both single and double quotes same.

S=“hello”
S=‘hello’

Triple Quotes
It is used to create string with multiple lines.

e.g.
Str1 = “””This course will introduce the learner to text mining and text manipulation basics.
The course begins with an understanding of how text is handled by python”””
String comparison
We can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string
lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj" . The first two characters from str1 and str2 ( M
and M ) are compared. As they are equal, the second two characters are compared. Because they are
also equal, the third two characters ( r and n ) are compared. And because 'r' has greater ASCII value
than ‘n' , str1 is greater than str2 .
e.g.program

print("Maria" == "Manoj") #False


print("Maria" != "Manoj") #True
print("Maria" > "Manoj") #True
print("Maria" >= "Manoj") #True
print("Maria" < "Manoj") #False
print("Maria" <= "Manoj") #False
print("Maria" > "") #True
Updating Strings
String value can be updated by reassigning another value in
it.
e.g.
var1 = 'Comp Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )

OUTPUT
('Updated String :- ', 'Comp Sc with Python')
String Special Operators
e.g. a=“comp” B=“sc”

Operato Descriptio Example


r n
+ Concatenation – to add two strings a + b = comp sc
* Replicate same string multiple times (Repetition) a*2 = compcomp

[] Character of the string a[1] will give o


[:] Range Slice –Range string. End index not include. a[1:4] will give
omp
in Membership check p in a will give
True
not in Membership check for non availability M not in a will
give True
% Format the string

print ("My Subject is %s and class is %d" % ('Comp Sc', 1))


Build in methods :

Function Description
len(str) Return total length of the string.
max(str) Return item with maximum value in the string.
min(str) Return item with min value in the string.
sorted(str) Returns after sorting the string. sorted( string, reverse=True) = desc
sorted. List is returned with each character as individual element
del(str) Deletes the string. Syntax error if try to return
Method Remark Example
str.capitalize() Will return capitalized string r=a.capitalize() will be “Comp I like”
str.title() Will return title case string r=a.title() will be “Comp I Like”

str.upper() Will return string in upper case r=a.upper() will be “COMP I LIKE”
str.lower() Will return string in lower case r=a.lower() will be “comp i like ”
str.count(str) will return the total count of a r=a.count(‘I’) will be 1 as case sensitive
str.count(str,start given element in a string.
,end)
str.find(substr) To find the substring r=a.find (‘m’) will be 2
position(starts from 0 index) or start r=a.find(‘n’) will be -1 (does not exist)
str.find(sstr,from,
from given index. Returns index r=a.find(‘o’,2) will return -1 (does not
end)
number and -1 if not found exist after index 2)
str.replace(old,ne Return the string with replaced r=b.replace(‘I’,’you’) will be‘comp
w) sub strings you like’

str.index(str2) Returns index position of substring. r=a.index(‘om’)will be 1


Error if not found.
Method Remark Example
b=‘**comp’;
str.lstrip(char/s) Returns a copy of the string with
str.rstrip(char/s) r=b.lstrip(“**”) will be‘comp’
leading/trailingcharacters removed until it
reaches a non matching character on left r=b.lstrip(“oc”) will be ‘mp’
side (char can be given in any combination) r=b.lstrip(“cmo”) will be ‘omp’

Removes specific character from leading and b=‘**comp**’;


str.strip(char/s) trailing position and return the new string
r=b.strip(“**”) will be‘comp’

b=‘my comp ; my ’;
str.split() Returns list of strings split from whitespace if no r=b.split() will be
str.split(“;’’) argument and from argument if passed. [‘my’,‘comp’,’;’,my’]
Argument not an element in the string. Split from
all occurrence of argument r=b.split(;) will be[‘my
comp’,’my’]

str.partition(str) Returns tuple. Partition the string on first b=‘my comp my’;
occurrence of substring. Only 3 parts – before r=b.partition(‘comp’) will be
str, after str and str. Partion from first (‘my’,‘comp’,’my’)
occurrence of str.
Following methods are used when we iterate through a string to find if the character is alpha,
number ,space etc
All of them return Boolean value

Method Result Example

str.isalnum() Checks if string consists of only alphanumeric characters (no for i in s:


symbols) NOTE:s=“AB4@#” gives False for isalnum as special if i.isalnum():
symbols present in the string print(“I alpha/num”,i)
str.isalpha() Checks if string consists of only alphabetic characters (no for i in s:
symbols) NOTE:s=“AB@#” gives False for isalpha as special if i.isalpha():
symbols present in the string print(“I alphabet”,i)
str.isnumeric() Checks if string consists of only numeric characters s=“45#$@” gives False
str.isdigit()
str.isspace() Checks if string consists of only whitespace characters s=“ “ gives True

str.istitle() Checks if string is in title case s=“He She” gives True

str.isupper() Checks if string’s alphabetic characters are all upper case. s=“ab#$@” gives True
(Special characters ignored)
str.islower() Checks if string’s alphabetic characters are all lower s=“AB#$@” gives True
case.(Special characters ignored)
#Python Program to find number of vowels in a string
str=input("Enter string:")
count1=0
vol=“aeiouAEIOU”
for i in str:
if i in vol:
count1=count1+1
print("The number of vowels are:")
print(count1)
#Python Program to find number of consonants in a string
str=input("Enter string:")
count1=0
vol=“aeiouAEIOU”
for i in str:
if i not in vol:
count1=count1+1
print("The number of consonants are:")
print(count1)
#Python Program to find number upper letters, lower letters and digits in
a string
str=input("Enter string:")
count1=0
count2=0
count3=0
Count4=0
for i in str:
if i.islower():
count1=count1+1
elif i.isupper():
count2=count2+1
elif i.isdigit():
count3=count3+1
else:
count4=count4+1
print(“Lowercase letters:”,count1)
print(“Uppercase letters:”,count2)
print(“Digits:”,count3)
print(“Others:”,count4)

You might also like