31
loading...
This website collects cookies to deliver better user experience
slices
, or substrings
—instead of the whole string.<str>[start:stop:step]
<str>
—starting at index start
, extending up to stop-1
in steps of step
.start
index is optional: the slice starts from the beginning of the string by default.stop
index is also optional: the slice extends up to the end of the string by default.step
value is optional too. The default value of step is 1
and includes all characters in the string.my_str = "Python3"
enumerate()
and examine the characters at each index in the string.for idx,char in enumerate(my_str):
print(f"At index {idx}: letter {char}")
# Output
At index 0: letter P
At index 1: letter y
At index 2: letter t
At index 3: letter h
At index 4: letter o
At index 5: letter n
At index 6: letter 3
enumerate()
function in conjunction with the for
loop. This lets you loop through iterables, and access items along with their indices simultaneously—without having to use the range()
function to get the indices.# With `start` and `stop` indices
print(my_str[1:6])
# Output: ython
# Without `stop` index
print(my_str[1:])
# Output: ython3
# Without `start` index
print(my_str[:5])
# Output: Pytho
# With `step = 2`, slice includes every second character
print(my_str[::2])
# Output: Pto3
# Without `start`, `stop` and `step`: slice is entire string
print(my_str[::])
# Output: Python3
step
to a negative value, you can get slices starting from the end of the string—reverse substrings.step = -1
you get a slice starting from the end of the string, and including every character.print(my_str[::-1])
# Output: 3nohtyP
<str>[start:stop:step]
is the syntax to obtain string slices or substrings in Python.