PythonString methods
String slicing [start:stop:step]
Getting fragments of a string by index.
- Returns
- A character or a new string.
- Changes the original
- No
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
#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 thestopcharacter, sotext[:3]is the first three characters. - Reversing a string is
text[::-1].
Related entries
#- List slicing [start:stop:step]Getting, replacing, and deleting fragments of a list by index.
- str.find()Returns the index of the first occurrence of a fragment, or -1.
- reversed()Returns an iterator that walks through a sequence from the end.
- len()Returns the number of items in a collection, or the number of characters in a string.
Spotted a mistake or missing an example? Write to us.