python logo

python string slice


Python hosting: Host, run, and code Python in the cloud!

A string in Python is a sequence of characters. It is one of the most commonly used data types to represent and display textual information.

In Python, strings can be enclosed in single ('), double (") or triple (''' or """) quotes.

Recommended Course: Python Programming Bootcamp: Go from zero to hero

Understanding String Indexing in Python

Each character in a Python string has an associated index. For example, the characters in the word 'python' are indexed as shown below:

Python string indexing

Accessing Characters in a String

In Python, indexing starts at 0. Therefore, the character at the 0th index of a string is its first character. Let’s see an example to understand this better:

1
2
3
4
s = "Hello Python"
print(s) # Outputs: Hello Python
print(s[0]) # Outputs: H
print(s[1]) # Outputs: e

String Slicing in Python

Slicing is a mechanism to extract a part (or sub-string) of a string using its indices. The general syntax for string slicing is:

1
s[startIndex : endIndex]

Here:

  • startIndex refers to the starting index from where the slice should begin.
  • endIndex refers to the end position. However, note that the character at endIndex is not included in the slice.

If you skip the startIndex, the slice starts from the beginning of the string. If you skip the endIndex, the slice extends up to the end of the string. Here are some examples demonstrating string slicing:

1
2
3
4
s = "Hello Python"
print(s[0:2]) # Outputs: He
print(s[2:4]) # Outputs: ll
print(s[6:]) # Outputs: Python

For more hands-on experience with Python, you can Download Python Exercises.

← Back to Python Strings | Proceed to Python Variables →






Leave a Reply: