How to Slice Strings in Python
See Python: Tips and Tricks for similar articles.In Python, when you need to get a sequence of characters from a string (i.e., a substring), you get a slice of the string using the following syntax:
substring = original_string[first_pos:last_pos]
When slicing in Python, note that:
- The slice begins with the character at
first_pos
and includes all the characters up to but not including the character atlast_pos
. - If
first_pos
is left out, then it is assumed to be 0. So"hello"[:3]
would return"hel"
. - If
last_pos
is left out, then it is assumed to be the length of the string, or in other words, one more than the last position of the string. So"hello"[3:]
would return"lo"
.
The following code shows how to get substrings using slicing.
phrase = "Monty Python"
first_5_letters = phrase[0:5]
#[Monty] Python
print(first_5_letters)
letters_2_thru_4 = phrase[1:4]
#M[ont]y Python
print(letters_2_thru_4)
letter_5_to_end = phrase[4:]
#Mont[y Python]
print(letter_5_to_end)
last_3_letters = phrase[-3:]
#Monty Pyt[hon]
print(last_3_letters)
first_3_letters = phrase[:3]
#[Mon]ty Python
print(first_3_letters)
three_letters_before_last = phrase[-4:-1]
#Monty Py[tho]n
print(three_letters_before_last)
copy_of_string = phrase[:]
#[Monty Python]
print(copy_of_string)
The expected output for each print statement is shown in square brackets in the preceding comment.
Related Articles
- Fixing WebVTT Times with Python
- Using Python to Convert Images to WEBP
- Scientific Notation in Python
- Understanding Python’s __main__ variable
- Converting Leading Tabs to Spaces with Python
- pow(x, y, z) more efficient than x**y % z and other options
- A Python Model for Ping Pong Matches
- Bulk Convert Python files to IPython Notebook Files (py to ipynb conversion)
- Python’s date.strftime() slower than str(), split, unpack, and concatenate?
- Basic Python Programming Exercise: A Penny Doubled Every Day
- Bi-directional Dictionary in Python
- How to find all your Python installations on Windows (and Mac)
- Associate Python Files with IDLE
- Change Default autosave Interval in JupyterLab
- Python: isdigit() vs. isdecimal()
- Python Clocks Explained
- Python Color Constants Module
- Maximum recursion depth exceeded while calling a Python object
- When to use Static Methods in Python? Never
- Finally, a use case for finally – Python Exception Handling
- Creating an Email Decorator with Python and AWS
- Python Coding Challenge: Two People with the Same Birthday
- How to Create a Simple Simulation in Python – Numeric Data
- Collatz Conjecture in Python
- Simple Python Script for Extracting Text from an SRT File
- Python Virtual Environments with venv
- Mapping python to Python 3 on Your Mac
- How to Make IDLE the Default Editor for Python Files on Windows
- How to Do Ternary Operator Assignment in Python
- How to Convert Seconds to Years with Python
- How to Create a Python Package
- How to Read a File with Python
- How to Check the Operating System with Python
- How to Use enumerate() to Print a Numbered List in Python
- How to Repeatedly Append to a String in Python
- Checking your Sitemap for Broken Links with Python
- How to do Simultaneous Assignment in Python
- Visual Studio Code - Opening Files with Python open()
- How to Slice Strings in Python (this article)
- How Python Finds Imported Modules
- How to Merge Dictionaries in Python
- How to Index Strings in Python
- How to Create a Tuple in Python