Strings and Characters
"""A Python program to
access each element of a string
in forward and reverse orders using
while loop"""
#indexing on string
s="Rama Rao"
#Accessing each character using while
loop
n=len(s) #n is no of chars in string s
i=0 #i varies from 0 to n-1
while i>=-n:
print(s[i],end=' ')
i=i-1 #i-=1
print() #put curson into next line
#access in reverse order using negative
index
i=1 #where i varies from 1 to n
n=len(s) # no of characters in String s
while i<=n:
print(s[-i],end=' ')
i=i+1 #i+=1
"""output:
R o a R
a m a R
o a R
a m a R
>>> """
Indexing in Strings
Index represents the position number.
Index is written using square braces []. By specifying the position number
through an index, we can access the particular elements or characters of a
string.
Negative
number:
When we use index as a negative number,
it can access the elements in the reverse order that is s[-1] refers to the
last element.
"""A Python program to
access each element of a string
in forward and reverse orders using for
loop"""
#indexing on string
s="Rama Rao"
#access each letter using for loop
for i in s:
print(i,end='')
print()#new line
#access in reverse order
for i in s[::-1]:
print(i,end='')
"""output:
Rama Rao
oaR amaR
>>>
>>> """
Slicing
the String
A slice represents a part or piece of a
string.
String[start:stop:stepsize]
S=’Rama Rao’
S[0:7:1]
>>> s[0:7:1]
'Rama Ra'
>>> s[0:7:2]
'Rm a'
>>> s[::]#access string from 0th
to last character
'Rama Rao'
>>> s[::2] #Access entire string
in steps of 2
'Rm a'
>>> s[2::]#access string from
s[2] to ending
'ma Rao'
>>> s[2:4:1] #access from s[2]
to s[3] in steps of 1
'ma'
>>>
Suppose if you write the following
statements:
>>> s[:3:] #accessing string
from s[0] to s[2] in steps of 1
'Ram'
>>>
It is possible to use reverse slicing to
retrieve the elements from the string in reverse order.
>>> s[-4:-1]
' Ra'
>>>
>>> s[-8::]
'Rama Rao'
>>>
Concatenation
of Strings
>>> a='mahesh'
>>> b='babu'
>>> c=a+b
>>> print(c)
maheshbabu
>>>
We can use ‘+’ on strings to attach a
string at the end of another string. If we use ‘+’ operator on numbers it is
called addition operators, When we used on strings, it is called ‘concatenation’
operator since it joins the strings.
Removing
Spaces from a string:
s=" Rama "
>>> print(s.strip())
Rama
>>> print(s)
Rama
>>> print(s.lstrip())
Rama
>>> print(s.rstrip())
Rama
>>>
Next Topic:
Functions
Previous Topic:
The else
suite