Page 152 - CodePilot V5.0 C8
P. 152
Program 9 A program to access characters of a string.
Program9.py Output
File Edit Format Run Options Window Help
Positive Indexing:
str = "Python" P
print("Positive Indexing:")
h
print(str[0])
Negative Indexing:
print(str[3])
print("Negative Indexing:") n
print(str[-1]) t
print(str[-4])
SLICING
To extract a portion of the string consisting of multiple characters, you can use slicing. Specify
a range of indexes (positive or negative) to extract the characters from the string. The starting
character of the range is included but the ending index is excluded from the output. The syntax
for slicing is:
str_name[start:end:step]
Where, str_name is the string to slice from, start is the index of the starting character of the slice,
end is the index of the next character and step is for extracting every nth character.
Program 10 A program to demonstrate string slicing and indexing operations.
Program10.py Output
File Edit Format Run Options Window Help Computer Science
C
str = 'Computer Science'
omp
# Print entire string
print(str) Cmue cec
# Print first character Science
print(str[0])
# Print index 1 to 3
print(str[1:4])
# Every 2nd character
print(str[0:15:2])
# Print last 7 characters
print(str[-7::])
STRING OPERATORS
Strings can be manipulated using a variety of operators. There are two basic string operators in
Python, + and *. Python uses + for concatenation and * for replication.
150
CodePilot (V5.0)-VIII

