How to Slice Strings in Python

See Python: Tips and Tricks for similar articles.
Looking to improve your Python skills? Check out Webucator’s Python classes.

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:

  1. The slice begins with the character at first_pos and includes all the characters up to but not including the character at last_pos.
  2. If first_pos is left out, then it is assumed to be 0. So "hello"[:3] would return "hel".
  3. 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

  1. Scientific Notation in Python
  2. Understanding Python’s __main__ variable
  3. Associate Python Files with IDLE
  4. Python: isdigit() vs. isdecimal()
  5. Python Color Constants Module
  6. Python: pow(x, y, z) less efficient than x**y % z
  7. A Python Model for Ping Pong Matches
  8. Bulk Convert Python files to IPython Notebook Files (py to ipynb conversion)
  9. Collatz Conjecture in Python
  10. Finally, a use case for finally – Python Exception Handling
  11. Python Clocks Explained
  12. Python’s date.strftime() slower than str(), split, unpack, and concatenate?
  13. Bi-directional Dictionary in Python
  14. Maximum recursion depth exceeded while calling a Python object
  15. Basic Python Programming Exercise: A Penny Doubled Every Day
  16. Creating an Email Decorator with Python and AWS
  17. How to Create a Simple Simulation in Python – Numeric Data
  18. Python Coding Challenge: Two People with the Same Birthday
  19. How to find all your Python installations on Windows
  20. Change Default autosave Interval in JupyterLab
  21. Interactive Quiz using IPython Notebook
  22. When to use Static Methods in Python? Never
  23. Converting Leading Tabs to Spaces with Python
  24. Simple Python Script for Extracting Text from an SRT File
  25. Python Virtual Environments with venv
  26. Mapping python to Python 3 on Your Mac
  27. How to Make IDLE the Default Editor for Python Files on Windows
  28. How to Do Ternary Operator Assignment in Python
  29. How to Convert Seconds to Years with Python
  30. How to Create a Python Package
  31. How to Read a File with Python
  32. How to Check the Operating System with Python
  33. How to Use enumerate() to Print a Numbered List in Python
  34. How to Repeatedly Append to a String in Python
  35. Checking your Sitemap for Broken Links with Python
  36. How to do Simultaneous Assignment in Python
  37. Visual Studio Code - Opening Files with Python open()
  38. How to Slice Strings in Python (this article)
  39. How Python Finds Imported Modules
  40. How to Merge Dictionaries in Python
  41. How to Index Strings in Python
  42. How to Create a Tuple in Python