String slicing [start:stop:step]

Getting fragments of a string by index.

Returns
A character or a new string.
Changes the original
No
On this page

Example

#
Python
word = "CodeWorlds"

print(word[0], word[-1])
print(word[:4])
print(word[4:])
print(word[::-1])
print(word[1:8:2])
Resultsaved result, you can check it
C s
Code
Worlds
sdlroWedoC
oeol

Definition and usage

#

Characters in a string are indexed starting at 0. You can read a single character with text[0], and the last one with text[-1], because negative indexes count from the end.

The slice text[start:stop] returns the fragment from index start to stop, without the character at index stop. Omitting start means the beginning, and omitting stop means the end of the string. The third value is the step: text[::2] takes every second character, and text[::-1] reverses the string.

Slices do not raise errors for out-of-range indexes, they just return a shorter or empty string. The same syntax works for lists and tuples.

Syntax

#
Syntax
string[index]
string[start:stop]
string[start:stop:step]

More examples

#
Out-of-range slices
Python
code = "US"
print(code[:10])
print(repr(code[5:]))
Resultsaved result, you can check it
US
''

Good practices

#
  • Remember: [start:stop] does not include the stop character, so text[:3] is the first three characters.
  • Reversing a string is text[::-1].

Related entries

#

Spotted a mistake or missing an example? Write to us.