Sunday, 24 November 2019

11th python: Traversing string using for, range function and slice operator

# A
# Python Program for string traversing:
 #Using for loop to traverse over a string in Python

string_to_trav = "Data Science"
for char in string_to_trav:
    print(char)

Output
>>>
== RESTART: C:/Users/Student/AppData/Local/Programs/Python/Python37-32/t.py ==
D
a
t
a

S
c
i
e
n
c
e

#B
# Using range() to traverse over a string in Python

string_to_trav = "Data Science"
for char_index in range(len(string_to_trav)):
   print(string_to_trav[char_index])

Output
>>>
== RESTART: C:/Users/Student/AppData/Local/Programs/Python/Python37-32/t.py ==
D
a
t
a

S
c
i
e
n
c
e


#C
# Using slice [] operator to traverse over a string partially

string_to_trav = "Python Data Science"
for char in string_to_trav[0 : 6 : 1]:
   print(char)

== RESTART: C:/Users/Student/AppData/Local/Programs/Python/Python37-32/t.py ==
P
y
t
h
o
n

No comments:

Post a Comment