Professional Documents
Culture Documents
CHAPTER 7
STRINGS
PROPRIETARY MATERIAL © 2018 The McGraw Hill Education, Inc. All rights reserved. No part of this PowerPoint slide may be displayed, reproduced or distributed in any form or
by any means, without the prior written permission of the publisher, or used beyond the limited distribution to teachers and educators permitted by McGraw Hill for their individual
course preparation. If you are a student using this PowerPoint slide, you are using it without permission.
Introduction to Strings
String is a sequence of characters.
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:
I OEYH N R GAM N
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
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
The split() method returns a list of all the words in the string.
>>>Str1.split()