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:
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 | s = "Hello Python" |
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 atendIndex
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 | s = "Hello Python" |
For more hands-on experience with Python, you can Download Python Exercises.
Leave a Reply: