0% found this document useful (0 votes)
4 views34 pages

Python Strings

Uploaded by

Pritika Sachdeva
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
4 views34 pages

Python Strings

Uploaded by

Pritika Sachdeva
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 34

PYTHON

STRING
S
STRINGS
A string is a sequence of characters. STRINGS ARE IMMUTABLE
A character is simply a symbol. For example, the English language has 26 characters.
Strings can be created by enclosing characters inside a single quote or double-quotes.

my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)
String Traversing
Traversing refers to iterating through the elements of a string , one character at a
time.

We can access individual characters using indexing and a range of characters using
slicing.
Index starts from 0. Trying to access a character out of index range will raise an
IndexError. The index must be an integer. We can't use floats or other types, this will
result into TypeError.
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
String Traversing
#Accessing string characters in Python
str = ‘Goodmorning'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
STRING OPERATORS
BASIC OPERATORS :
The two basic operators of Strings
are: + and *
+ is Concatenation and * is Replication
STRING REPLICATION
String Replication Operator (*) is used when you have two TYPES of
OPERANDS – a string and a Number i.e. as Number * string OR String
* Number
For Example :
1. Expression : “ abc “ * 2 Result – “abcabc”
2. Expression : 5 * “@” Result – “ @@@@@”

But the Expression “2” * “3” is INVALID and will hit with a
TYPEERROR:
STRING SLICES
Meaning of word ‘ slice ‘ which means - ‘ a part of ‘ . In same way in Python
refers to a part of the string , where strings are sliced using a range of
indices.
For Instance : For a string say Name , range is given as Name[n:m] where n
and m are integers and legal indices , python will return a slice of the string
by returning the characters falling between indices n and m- 1.
For Example: For the Word ‘ Amazing ‘

0 1 2 3 4 5 6

Word a m a z i n g

-7 -6 -5 -4 -3 -2 -1
STRING SLICES
Then ,
Word[0:7] will give ‘amazing’ ( letters starting from index o going up till 7 -1 =
6 : from indices 0 to 6 ( both inclusive )
Word[0:3] will give ‘ama’
Word [2:5] will give ‘azi’ – letters from index 2 to 4 (i.e 2 : 5 – 1 =4 ]
Word [ - 5 : - 1] will give ‘ azin ‘ – letters from indices – 5 , -4 , -3 , -2 excluding – 1

0 1 2 3 4 5 6

Word a m a z i n g

-7 -6 -5 -4 -3 -2 -1
STRING SLICES
Word [:7] will give ‘ amazing ‘ - missing index before colon is taken as
0.
Word [:5] will give ‘ amazi ‘
Word [3:] will give ‘ zing’ - missing index before colon is taken as 0.
Word [5:] will give ‘ ng’ - missing index before colon is taken as 0.

0 1 2 3 4 5 6

Word a m a z i n g

-7 -6 -5 -4 -3 -2 -1
STRING FUNCTIONS &
METHODS
Python offers many in – built functions and methods for string manipulation.
PYTHON BUILT – IN FUNCTIONS :
1. LEN() Function
It Returns the length of its arguments string, i.e. it return the returns the count of
characters in the string. The Len() function is a python standard library function.
SYNTAX : EXAMPLE:
Len(<string>) name = amazing
print(len(name))
STRING FUNCTIONS &
METHODS
2. CAPITALIZE() Method
It Returns the copy of the string with its first character capitalized.

SYNTAX : EXAMPLE:
<string>.capitalize() name1 = "india “

print(name1.capitalize())
STRING FUCNTIONS &
METHODS
3. Count() Method
It Returns the number of occurrences of the substring in string .
SYNTAX : <string>.count(sub,start[,end])
EXAMPLE:
string = ‘abracadabra’
‘abracadabra’.count(‘ab’) – count the occurrence of ‘ab’ in the whole string.
‘abracadabra’.count(‘ab’,4,8) – count the occurrence of ‘ab’ in string’s 4th to
8th characters
‘abracadabra’.count(‘ab’,4,8) – count the occurrence of ‘ab’ in string’s 6 th character onwards
STRING FUNCTIONS &
METHODS
Example 1: string = " happy for happy "
print(string.count("happy"))
Example 2: str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus“
Example 3: string = " Apple Mango Orange Mango Guava Guava Mango "
print(string.count("Apple"))
print(string.count("Orange"))
print(string.count("Mango"))
print(string.count("Guava"))
Example 4 : “Because the world is a place of silence, the sky at night when the birds have gone is a vast silent place.”
STRING FUNCTIONS &
METHODS
4. FIND() METHOD : It returns the Lowest index in the string where the
substring Sub is found within that slice Range of start and end. Returns
-1 if Sub is not Found.
SYNTAX : <string>.find(sub,start[,end])
sub : It’s the substring which needs to be searched in the given string.
start : Starting position where sub is needs to be checked within the string.
end : Ending position where suffix is needs to be checked within the string. EXAMPLE:
s = 'abcd1234dcba’
print(s.find('a')) # 0
print(s.find('cd')) # 2
print(s.find('1', 0, 5)) # 4
print(s.find('1', 0, 2)) # -1
PRACTICAL*
PRACTICAL : WAP to Check if substring is present in a string
or not ?
str= "Python is a Programming Language"
res = str.find("for")
if res >= 0:
print ("Programming is Present in String ")
else :
print ("Programming is not Present in String")
STRING FUNCTIONS &
METHODS
5. isalnum() METHOD : It returns TRUE if the characters in the String are
Alphanumeric ( Alphabets and numbers ) and there is at least one character,
FALSE otherwise. Please Note that the Space(‘ ‘) is not treated as alphanumeric.
SYNTAX : <string>.isalnum()

EXAMPLE:

string = "abc123"
print(string.isalnum())
STRING FUNCTIONS &
METHODS
6. isalpha() METHOD : It returns TRUE if all the characters
in the String are alphabetic and there is at least one
character, FALSE otherwise.
SYNTAX : string.isalpha() EXAMPLE

Parameters: string = 'Ayush'


isalpha() does not take any parameters print(string.isalpha())

Returns : string = 'Ayush0212'


print(string.isalpha())
1.True- If all characters in the string are alphabet.
2.False- If the string contains 1 or more non-alphabets. string = 'Ayush Saxena'
print( string.isalpha())
STRING FUNCTIONS &
METHODS
7 . Isdigit () METHOD : It returns TRUE if all the
characters in the String are DIGIT and there is at least
one character, FALSE otherwise.
SYNTAX : string.isdigit() EXAMPLE

string = 'Ayush'
print(string.isdigit())

string = 'Ayush0212'
print(string.isdigit())

string = ‘564322'
print( string.isdigit())
STRING FUNCTIONS &
METHODS
8 . Islower() METHOD : It returns TRUE if all cased
characters in the String are Lowercase and there is at
least one cased character, FALSE otherwise.
SYNTAX : string.islower() EXAMPLE

string = ‘hello'
print(string.islower())

string = ‘THERE'
print(string.islower())

string = ‘Human'
print( string.islower())
STRING FUNCTIONS &
METHODS
9 . Isupper() METHOD : It returns TRUE if all cased
characters in the String are Uppercase and there is at
least one cased character, FALSE otherwise.
SYNTAX : string.isupper() EXAMPLE

string = ‘hello'
print(string.isupper())

string = ‘THERE'
print(string.isupper())

string = ‘Human'
print( string.isupper())
STRING FUNCTIONS &
METHODS
10 . Lower() METHOD : It returns copy of the STRING
converted to lowercase.
SYNTAX : <string>.lower()

EXAMPLE

string = 'PYTHON'
print(string.lower())
STRING FUNCTIONS &
METHODS
11 . Upper() METHOD : It returns copy of the STRING
converted to uppercase.
SYNTAX : <string>.upper()

EXAMPLE

string = ‘python'
print(string.upper())
STRING FUNCTIONS &
METHODS
11 . Lstrip() , Rstrip() , Strip() METHOD :

Lstrip() : Returns a Copy of the String with leading whitespaces removed i.e. whitespaces
from the leftmost end are removed. <string>.lstrip()
Rstrip() : Returns a copy of the string with trailing whitespaces removed i.e. whitespaces
from the rightmost end are removed. <string>.rstrip()
Strip() : Returns a copy of the string with trailing and leading whitespaces removed i.e.
whitespaces from the rightmost and leftmost end are removed. <string>.strip()
EXAMPLE
str =' hello '
print(str.lstri
p())
STRING FUNCTIONS &
METHODS
12. Startswith() and endwith() Methods
Startswith() : Returns TRUE if the string starts with the substring Sub , otherwise returns
FALSE.
Endswith() : Returns TRUE if the String ends with the substring Sub , otherwise returns
FALSE.

EXAMPLE
<String>.startwith() & <string>.endwith()
str =' hello '
print(str.startswith(“a”))
STRING FUNCTIONS &
METHODS
13. ReplaceMethod()
It joins a String or character after each member of the string iterator i.e. a string
base sequence.
<String>.join(<string iterable>
EXAMPLE
str =' hello '
print(str.replace(“he”,”be”)
STRING FUNCTIONS &
METHODS
13. JoinMethod()
It joins a string or character after each member of the string iterator i.e string-
based sequence.
<String>.join(<string.iterable>)

str="My name is Pritika"


print('*'.join(str))
STRING FUNCTIONS &
METHODS
13. Split Method ()
It splits a string based on a given string or character and returns a list containing
split strings as members.
<String>.split(<string/char>)

str="Good Morning ! Have a Nice Day"


print(str.split())
STRING FUNCTIONS &
METHODS
13. Partition Method ()
It splits the string at the first occurrence of separator , and returns tuple
containing three items:
1. The part before the separator
2. The separator itself
3. The part after Separator
<String>.partition(<separator/string>)
str="I enjoy working in Python"
print(str.partition("working"))
DIFFERENCE BETWEEN
SPLIT() AND PARTITION ()
SPLIT’s () PARTITION’s ()
Split() will split the string at any Partition () will only split the string at the
occurrences of the given argument. first occurrence of the given argument.

It will return a LIST type containing the It will return a TUPLE type containing the
split substrings. split substrings.

The Length of the list is equal to the It will always a returns a Tuple of length 3 ,
number of words , if split on whitespace. with the given separator as the middle
value of the tuple.
PRACTICAL
Ques 11: WAP to count the Number of Vowels and Constants in
a String. str=input("Please enter a string as you wish: ");
vowels=0
constants=0
for i in str:
if(i == 'a'or i == 'e'or i == 'i'or i == 'o'or i == 'u' or
i == 'A'or i == 'E'or i == 'I'or i == 'O'or i == 'U' ):
vowels=vowels+1;#vowel counter is incremented by 1
else:
constants=constants+1;
#consonant counter is incremented by 1
print("The number of vowels:",vowels);
print("\nThe number of consonant:",consonants);
PRACTICAL
Ques 12: Write a program to check if the word 'orange' is
present in the "This is orange juice"
a = "This is orange juice"
print ('orange' in a.split())
PRACTICAL
Ques 13: Count the occurrences of each word in a given
sentence
“But good morning! Good morning to ye and thou! I’d say to all
my patients, because I was the worse of the hypocrites, of all
the hypocrites, the cruel and
stringphony hypocrites,
= "But good I was
morning! Good the very
morning to ye
worst.” and thou! I’d say to all my patients, because I was
the worse of the hypocrites, of all the hypocrites,
the cruel and phony hypocrites, I was the
veryworst."
print(string.count("But"))
print(string.count("all"))
print(string.count("good"))
print(string.count("thou"))
PRACTICAL
Ques 14: Write a program to Check if substring is present in a
string or not
str= "Hello , My Name is Pritika"
res = str.find(" Name ")
if res >= 0:
print ("Name is Present in String ")
else :
print ("Name is not Present in String")
PRACTICAL
line = input("Enter a line")
Ques 15: Write a program to read lowercount = uppercount = digicount = 0
a line and print its statistics like : for a in line :
Number of Uppercase letters if a.islower():
lowercount = lowercount + 1
Number of Lowercase Letters elif a.isupper():
uppercount = uppercount + 1
Number of Digits
elif a.isdigit():
digicount = digicount + 1

print("number of uppercase letters", upperc


print("number of lowercase letters", lowerco
print("number of Digits", digicount)

You might also like