In Python, strings are sequences of characters. Like other sequences, strings can be indexed and sliced.
Each character in a string has an assigned index starting from 0 for the first character.
For the string 'Python':
P(0) y(1) t(2) h(3) o(4) n(5)
To access characters by their index:
text = 'Python' print(text[0]) # Outputs: 'P' print(text[5]) # Outputs: 'n'
You can also use negative indices to count from the end:
P(-6) y(-5) t(-4) h(-3) o(-2) n(-1)
Using negative indices:
print(text[-1]) # Outputs: 'n' print(text[-6]) # Outputs: 'P'
Slicing allows you to obtain a substring from a string. The syntax is:
string[start:stop:step]
start: The beginning index of the slice (inclusive).stop: The ending index of the slice (exclusive).step: The interval between characters in the slice.Examples:
text = 'Python' print(text[1:4]) # Outputs: 'yth' (from index 1 to 3) print(text[2:]) # Outputs: 'thon' (from index 2 to the end) print(text[:4]) # Outputs: 'Pyth' (from the start to index 3) print(text[::2]) # Outputs: 'Pto' (every second character) print(text[::-1]) # Outputs: 'nohtyP' (reverse the string)
If omitted, start defaults to the beginning of the string, stop defaults to the end of the string, and step defaults to 1.
IndexError.varbinarymax objectmapper google-maps-markers positional-argument apache-stanbol httpurlconnection pytest rename io-redirection associations