Home | | Computer Science 12th Std | Accessing characters in a String

Python - Accessing characters in a String | 12th Computer Science : Chapter 8 : Core Python : Strings and String Manipulation

Chapter: 12th Computer Science : Chapter 8 : Core Python : Strings and String Manipulation

Accessing characters in a String

Once you define a string, python allocate an index value for its each character.

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



Example 1 : Program to access each character with its positive subscript of a giving string

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


Example 2 : Program to access each character with its negative subscript of a giving string

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

 

Tags : Python , 12th Computer Science : Chapter 8 : Core Python : Strings and String Manipulation
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
12th Computer Science : Chapter 8 : Core Python : Strings and String Manipulation : Accessing characters in a String | Python


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.