Accessing characters in a String
Once you define a string, python allocate an
index value for its each character. These index values are otherwise called as
subscript which are used to access and manipulate the strings. The subscript
can be positive or negative integer numbers.
The positive subscript 0 is assigned to the first character and n-1 to the last character, where n is the number of characters in
the string. The negative index assigned from the last character to the first
character in reverse order begins with -1.
Example
str1 = input ("Enter a
string: ")
index=0
for i in str1:
print
("Subscript[",index,"] : ", i)
index + = 1
Output
Enter a string: welcome
Subscript [ 0 ] : w
Subscript [ 1 ] : e
Subscript [ 2 ] : l
Subscript [ 3 ] : c
Subscript [ 4 ] : o
Subscript [ 5 ] : m
Subscript [ 6 ] : e
str1 = input ("Enter a
string: ")
index=-1
while index >= -(len(str1)):
print
("Subscript[",index,"] : " + str1[index])
index += -1
Output
Enter a string: welcome
Subscript [ -1 ] : e
Subscript [ -2 ] : m
Subscript [ -3 ] : o
Subscript [ -4 ] : c
Subscript [ -5 ] : l
Subscript [ -6 ] : e
Subscript [ -7 ] : w
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.