![]() |
|
[Tut] Python | Split String at Position - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python | Split String at Position (/thread-100155.html) |
[Tut] Python | Split String at Position - xSicKxBot - 10-29-2022 Python | Split String at Position Rate this post Summary: You can split a given string at a specific position/index using Python’s string–slicing syntax. Minimal Example: Code: # 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: 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: ◈[b]Example 1[/b] 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. Code: # Input
s = "split string at position"
# Output
split string
at positionThe following problem asks us to split the string based on the position of a certain character (“ Code: ,Code: orCode: # 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 6546Now, let’s dive into the different ways of solving this problem. [b]Method 1: Using String Slicing[/b] 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.◈[b]Example 1 Solution[/b] 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: Code: s = "split string at position"
print(s[:12])
print(s[13:])Output: Code: split string
at positionApproach: Use the Code: index()Code: ,Code: orCode: 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: Code: Personnel: Bob is the Relationship Manager
Email: contact him at bob@xyz.abc Contact Info: call him at 6546Note: The Code: index()Code: index()◈[b]Method 2: Using regex[/b] 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 Code: re.search(pattern, string) Related read: Python Regex SearchPre-requisite: Code: match_object.start()Code: match_object.end()A Quick Look at The Official Documentation: source: https://docs.python.org/3/library/re.html#re.Match.start◈[b]Example 1 Solution[/b] Approach:
Code: 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: Code: split string
at positionThe 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 Code: start()Code: end()Code: 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: Code: Personnel: Bob is the Relationship Manager
Email: contact him at bob@xyz.abc or
Contact Info: call him at 6546Woohoo! 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). |