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

Strings

The document provides an overview of string manipulation in Python, including how to create strings, access characters using indexing, and utilize built-in functions. It covers string operations such as slicing, concatenation, and comparisons, as well as methods for testing and modifying strings. Additionally, it includes examples of functions for counting characters, modifying cases, and removing letters from strings.

Uploaded by

Ritvik Bansal
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)
4 views24 pages

Strings

The document provides an overview of string manipulation in Python, including how to create strings, access characters using indexing, and utilize built-in functions. It covers string operations such as slicing, concatenation, and comparisons, as well as methods for testing and modifying strings. Additionally, it includes examples of functions for counting characters, modifying cases, and removing letters from strings.

Uploaded by

Ritvik Bansal
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/ 24

Strings

Dr. Kusum Lata


Assistant professor, USME, EDC
String is a sequence of characters
• Create a string using str()
S1=str ( ) #Creates an Empty string Object
S2=str (“Hello”) #Creates a String Object for Hello
➢Alternative way to create a string object is by assigning a string value to a
variable.
S1 = “ ” # Creates a Empty String
S2=”Hello” # Equivalent to S2= str(“Hello”)
➢Access the characters of a string one at a time using the index operator
Python Basic Built-in Functions for String

• min() and max() functions to return largest and smallest character in a string.
• len() function to return number of characters in a string.
>>> a = "PYTHON"
>>> len (a) #Return length i.e. number of characters in string a
6
>>> min (a) #Return smallest character present in a string
'H'
>>> max (a) #Return largest character present in a string
'Y'
The Index[] Operator

• The characters in a string can be accessed one at a time through


the index operator.

• The first character of a string is stored at 0th position.

• The last character of a string is stored at position one less than


length of the string.

• Graphical representation how string are stored is shown below.


Continued

Example:
>>> S1="Python"
>>>S1[0] #Access the first element of the string.
'P'
>>>S1[5] #Access the last element of the String.
'n‘
Example:
>>> a='IIT'
>>> a [3]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a[3]
IndexError: string index out of range
Access Characters via Negative Index
➢Negative index accesses the characters from the end
of the string counting in backward direction.
➢The index of last character of any non-empty string is
always -1 as shown below.

Example:
• >>> S="PYTHON"
• >>> S[-1] #Access the last character of a String ‘S’
• 'N'
Continued
Example:
S="IIT-Bombay"
>>> S[-3]
>>>‘b’
Traversing string with for and while Loop
Loop is used to traverse all characters in a string
Program:-To traverse all the elements of a String using for loop.
S="India"
for ch in S:
print(ch, end="")
Output:
India

Program :-To Traverse every second character of a string using for loop.
S="ILOVEPYTHONPROGRAMMING"
for ch in range(0,len(S),2) :#Traverse each Second character
print(S[ch],end=" ")

Output:
IOEYHNRGAMN
Traversing with a while Loop
Programmers can also use while loop to traverse all the elements of a string.

Program : To traverse all the elements of a String using while loop.


S="India"
index=0
while index<len(S):
print(S[index],end="")
index=index+1
Output:
India
Immutable Strings
Character Sequences fall into two categories such as mutable and immutable .
Mutable means changeable and immutable means unchangeable.
So the strings are immutable sequences of characters.
What happens if you try to change the contents of the string?

Example:
Str1="I Love Python"
Str1[0]="U"
print(Str1)

ERROR:
TypeError: 'str' object does not support item assignment

one cannot change the existing string.


The String Operators
➢ String contains slicing operator, slicing with step sizes operator to obtain
subset of string.
➢ It also has basic Concatenation ‘+’, ‘in’ and repetition ‘*’ operators.
The following section describes string operators in details

String Slicing Operator [start: end]


The slicing operator returns a subset of a string, called “slice” by specifying
two indices i.e. start and end.
Its syntax is used to return the subset of a string. Syntax is as follows.
Name_of_Variable_of_a_String [Start_Index: End_Index]
Example:
>>> S=“NEW-DELHI "
>>> S[4:8] #Returns a Subset of a String
‘DELHI‘
String Slicing With Step Size
• A programmer can select every second character from a string.
• This can be possible using “Step Size”.
• In slicing first two parameters are start index and end index.
• Thus, add third parameter as “Step Size” to select a characters from a string with step size
• Syntax:
• Name_of_Variable_of_a_String [Start_Index:End_Index:Step_Size]
• Example:
>>>S="IIT-BOMBAY"
>>> S[0:len(S)-1:2]
>>>'ITBMA‘
The statement S[0:len(S):2]indicates to select the portion of string which starts at index 0, ends on
index 9.
The String +, * and in Operators
• The + Operator - The concatenation operator ‘+’ is used to join two Strings.
Example:
>>> S1="IIT " #The String “IIT” assigned to S1
>>> S2="Delhi“ #The String “Delhi” assigned to S1
>>> S1+S2
'IIT Delhi'
• The * Operator - The multiplication(*) operator is used to concatenate the same string multiple
times. It is also called as “repetition operator”.
• Example:
>>> S1="Hello"
>>> S2=3*S1 #Print the String “Hello” three times
>>> S2
'HelloHelloHello'
The in and not in Operator
• Both Operators in and not in are used to check whether a string is present in another string.
• Example:
>>> S1="Information Technology"
#Check if the string “Technology” is present in S1
>>> "Technology" in S1
True

#Check if the string “Technology” is present in S1


>>> "Engineering" in S1
False

>>> S1="Information Technology"


# Check if the string “Hello” is not present in S1
>> "Hello" not in S1
True
String Comparisons

• Operators such as ==,<,>,<=,>=and != are used to compare the


strings.
• Python compares strings by comparing their corresponding
characters.
Example:

>>> S1="abcd"
>>> S2="ABCD"
>>> S1>S2
True
String Testing
• A string contains digits, alphabets or combination of both of these. Thus various
methods are available to test it the entered string contains digits or alphabets.
Method Meaning Example
isalpha() Returns true if the
characters in the string are
alphabets
isdigit() Returns true if the
characters in the string are
digits

islower() Returns true if all the


characters in the string is
lowercase

isupper() Returns true if the


characters in the string are
in upper case
Searching Substring in a String
Method Meaning Example

endswith(str) Returns true if the string ends with the


substring str

startswith(str) Returns true if the string starts with the


substring str

find(str) Returns the lowest index where the


string starts in the given string or return
-1 if the string str is not in the given
string

rfind(str) Returns the highest index where the


string starts in the string or return -1 if
the string str is not in the given string

count(str) Returns the number of occurrences of


str in the given string
Methods to convert a string into another string
Method Meaning Example
captalize() Returns a copy of the string with only first
character capitalized
lower() Returns a copy of the string with all the
letters converted to lowercase

upper() Returns a copy of the string with all the


letters converted to uppercase

title() Returns a copy of the string with first letter


capitalised in each word

swapcase( Upper case→lower case


) Lowercase→uppercase()

replace(str Returns a copy of the string that replaces all


old, str the occurrences of old string with new
new, string. The third parameter count is
Formatting string
Method Meaning Example

center(int width) Returns a copy of the string


centered in the field of the
given width

ljust(int width) Returns a copy of the string


left justified in the field of
the given width

rust(int width) Returns a copy of the string


left justified in the field of
the given width
Write a function countb(word) which takes word as argument and returns
number of ‘b’ in that word
Write a function count(word, letter) which takes word and letter as
arguments and returns number of occurrences of that letter in the word

def count (word, letter):


print(word)
print(letter)
count=0
for i in word:
if i==letter:
count+=1
return count
w=input("enter a string")
l=input("enter a character")
print("l is occurring", count(w, l),"times in", w)
Write a function modify_case(word) which changes the case of all the letters
of the word and returns the modified word.

def modify_case(word):
print(word)
w=word.swapcase()
return w
w=input("enter a string")
s=modify_case(w)
print("the modified string is", s)
Write a function eliminate (word, letter) which takes word and letter as
arguments and removes all the occurrences of that letter in the word and
returns the remaining letters in the word

def remove_letter(word,letter):
print(word)
print(letter)
w=word.replace(letter,"")
return w
w=input("enter a string")
l=input("enter a character")
s=remove_letter(w,l)
print("after removing", l,"the string is",s)
Write a function upper_vowels(word) which returns the word with all the
vowels capitalized
def capital_vowel(word):
print(word)
new=" "
for x in word:
if x='a' or x=='e' or x==‘o’ or x==‘u’ or x==‘i
new=new+x.upper()
else:
new=new+x
return new
w=input("enter a string")
s=capital_vowel(w)
print("after capitalizing vowels the string is", s)

You might also like