Accessing Python String Items
M3-R5.1 · Chapter 5: Sequence Data Types · 3 min read
Accessing Python String Items:We can access individual characters in a string using indexing and extract multiple characters using slicing.
Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.
Example of Accessing Python String Items:
|
A=Jai Prakash Mishra” #positive Index print(a[0]) print(a[1]) print(a[2]) |
#Negaitve Index print(a[-1]) print(a[-2]) print(a[-3]) |
Traversing a String: Traversing a string in Python means accessing each character in the string, one by one. This can be done using loops:
Traversing a String: Traversing a string in Python means accessing each character in the string, one by one. This can be done using loops:
Example-1:
|
Using a for loop name = "Naitik" for char in name: print(char) |
Using for with range() and indexing name = "Naitik" for i in range(len(name)): print(f"Character at index {i} is {name[i]}") |
Using a while loop name = "Naitik" i = 0 while i < len(name): print(name[i]) i += 1 |
Example-2:
|
str = “Karamraji” for ch in str : print(ch, end= ‘ ‘) Output: Karamraji |
str = "Karamraji" for ch in str : print(ch, end= "$ ") Output: K$ a$ r$ a$ m$ r$ a$ j$ i$ |
str = "Karamraji" for ch in str : print(ch,"**", end= "$ ") Output: K **$ a **$ r **$ a **$ m **$ r **$ a **$ j **$ i **$ |
|
|
str = "Karamraji" for ch in range (len(str)) : print(ch, end= " ") Output: 0 1 2 3 4 5 6 7 8 |
str = "Karamraji" for ch in range (len(str)) : print(str[ch], end= " ") Output: K a r a m r a j i |
# Reverse a String str="prakash" for i in range(-1,-len(str)-1,-1): print(str[i],end="") Output: hsakarp |
|
Q: Write a program to get the string from keyboard until user enter quit and Print the length of all entered string
|
while True: str=input("plz enter the string") if str=="quit": break print ("the length of string is ",len(str)) print("Done") |
:OUTPUT: plz enter the string jai the length of string is 3 plz enter the string prakash the length of string is 7 plz enter the string mishra the length of string is 6 plz enter the string quit Done |