Python | Split String at Position

5/5 - (2 votes)

Summary: You can split a given string at a specific position/index using Python’s stringslicing syntax.

Minimal Example:

# Method 1:
s = "split string at position"
print(s[:12])
print(s[13:])

# Method 2:
import re
s = "split string at position"
pos = re.search('at', s)
l = s[:pos.start()]
r = s[pos.start():]
print(l)
print(r)

# OUTPUT:
split string
at position

Problem Formulation

πŸ’¬Problem: Given a string, how will you split the given string at any given position?

Let’s have a look at a couple of examples that demonstrate what the problem asks you to do:

β—ˆExample 1

The following problem requires us to split the string into two parts. You have to cut the given string into two halves based on a certain index/position. The given cut position/index is 12.

# Input
s = "split string at position"
# Output
split string
at position

β—ˆExample 2

The following problem asks us to split the string based on the position of a certain character (β€œ,”) and a word (β€œor”) present in the string. Thus, in this case, you have not been given the exact position or index to split the string. Instead, you have to find the index/position of certain characters and then split the string accordingly based on the positions of the given characters and words and store the required sub-strings in different variables.

# Input
text = "Bob is the Relationship Manager, contact him at bob@xyz.abc or call him at 6546 "
# Output:
Personnel: Bob is the Relationship Manager
Email:  contact him at bob@xyz.abc
Contact Info:  call him at 6546

Now, let’s dive into the different ways of solving this problem.

Method 1: Using String Slicing

String slicing is the concept of carving a substring from a given string. Use slicing notation s[start :stop: step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start = 0, stop = len(string), step = 1.)

🌎 Related Tutorial: String Slicing in Python.

β—ˆExample 1 Solution

Approach: Use string slicing to cut the given string at the required position. To do this, you have to use the square-bracket syntax within which you can specify the starting and ending indices to carve out the required sub-strings as shown in the solution below.

Code:

s = "split string at position"
print(s[:12])
print(s[13:])

Output:

split string
at position

β—ˆExample 2 Solution

Approach: Use the index() method of the given character, i.e., “,” and the substring “or” within the given string. Then use this index to extract the required chunks of substrings by splitting the given string with the help of string slicing.

Code:

text = "Bob is the Relationship Manager, contact him at bob@xyz.abc or call him at 6546 "
# get the position of characters where you want to split the string
pos_comma = text.index(',')
pos_or = text.index('or')
# Slice the string based on the position of comma
personnel, email, phone = text[:pos_comma], text[pos_comma+1:pos_or], text[pos_or+2:]
print(f'Personnel: {personnel}\nEmail: {email}\nContact Info: {phone}')

Output:

Personnel: Bob is the Relationship Manager
Email:  contact him at bob@xyz.abc 
Contact Info:  call him at 6546 

Note: The index() method allows you to find the index of the first occurrence of a substring within a given string. You can learn more about Python’s index() method here: Python String index().

β—ˆMethod 2: Using regex

If a regular expression matches a part of your string, a lot of helpful information comes with it, for example, you can find out what’s the exact position of the match. The re.search(pattern, string) method is used to match the first occurrence of a specified pattern in the string and returns a match object. Thus, you can use it to solve the given problem.

🌎 Related read: Python Regex Search

Pre-requisite: match_object.start() is a method used to get the position of the first character of the match object and match_object.end() is the method to get the last character of the match object.

A Quick Look at The Official Documentation:

source: https://docs.python.org/3/library/re.html#re.Match.start

β—ˆExample 1 Solution

Approach:

  • Import the regex module and then create a match object by using the re.search() method. You can do this by passing the substring/character that lies at the given split index/position. In this case, the substring that lies at the split index is “at“.
  • We can then split the string by accessing the start position of the matched string object by calling the method pos.start() where pos denotes the matched object. 
  • Then to get the first half of the split string, you can use string slicing as s[:pos.start()]. Here, we sliced the original string from the start index of the given string until the index of the searched character (not included) that was extracted in the previous step.
  • Further, we need the second section of the split string. Thus, we will now slice the original string from the index of the searched character to the end of the string, like so: s[pos.start():]

Code:

import re

s = "split string at position"
pos = re.search('at', s)
l = s[:pos.start()]
r = s[pos.start():]
print(l)
print(r)

Output:

split string
at position

β—ˆExample 2 Solution

The idea is pretty similar to the solution of example 1. You just need to adjust the start and stop indices within the slice syntax with the help of the start() and end() methods to extract the required split sub-strings one by one.

Code:

import re
text = "Bob is the Relationship Manager, contact him at bob@xyz.abc or call him at 6546"
# Look for the match objects
_comma = re.search(',', text)
_or = re.search('or', text)
# slice to get first substring
personnel = text[:_comma.start()]
# slice to get second substring
email = text[_comma.end()+1:_or.start()]
# slice to get third substring
phone = text[_or.end():]
# Final Output
print(f'Personnel: {personnel}\nEmail: {email}\nContact Info: {phone}')

Output:

Personnel: Bob is the Relationship Manager
Email: contact him at bob@xyz.abc or
Contact Info:  call him at 6546

Conclusion

Woohoo! We have successfully solved splitting a string at the position using two different ways. I hope you enjoyed this article and it helps you in your coding journey. Please subscribe and stay tuned for more such interesting articles!

Related Reads:
β¦Ώ Python | Split String by Whitespace
β¦Ώ
 How To Cut A String In Python?
β¦Ώ Python | Split String into Characters


Google, Facebook, and Amazon engineers are regular expression masters. If you want to become one as well, check out our new book: The Smartest Way to Learn Python Regex (Amazon Kindle/Print, opens in new tab).