Strings
Strings
• 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
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.
Example:
Str1="I Love Python"
Str1[0]="U"
print(Str1)
ERROR:
TypeError: 'str' object does not support item assignment
>>> 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
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)