Professional Documents
Culture Documents
Application Based Programming in Python Chapter 7
Application Based Programming in Python Chapter 7
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 O EYH 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
>>> 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
The split() method returns a list of all the words in the string.
It is used to break up a string into smaller strings.
>>>Str1.split()