Python: Split A String By The Position Of A Character
How can I split a string by the position of a word? My data looks like this: test = 'annamarypeterson, Guest Relations Manager, responded to this reviewResponded 1 week agoDear Lor
Solution 1:
You can do this with strings (and lists) using slicing:
string = "hello world!"
splitat = 4
left, right = string[:splitat], string[splitat:]
will result in:
>>>left
hell
>>>right
o world!
Solution 2:
Maybe the simplest solution is to use string slicing:
test = 'annamarypeterson, Guest Relations Manager, responded to this reviewResponded 1 week agoDear LoreLoreLore,Greetings from Amsterdam!We have received your wonderful comments and wanted to thank you for sharing your positive experience with us. We are so thankful that you have selected the Andaz Amsterdam for your special all-girls weekend getaway. Please come and see us again in the near future and let our team pamper you and your girlfriends!!Thanks again!Anna MaryAndaz Amsterdam -Guest RelationsReport response as inappropriateThank you. We appreciate your input.This response is the subjective opinion of the management representative'
pos = test.find('ago') + 3
print(test[:pos], test[pos:])
Solution 3:
Got a built in function for you.
import re
test = 'annamarypeterson, Guest Relations Manager, responded to this reviewResponded 1 week agoDear LoreLoreLore,Greetings from Amsterdam!We have received your wonderful comments and wanted to thank you for sharing your positive experience with us. We are so thankful that you have selected the Andaz Amsterdam for your special all-girls weekend getaway. Please come and see us again in the near future and let our team pamper you and your girlfriends!!Thanks again!Anna MaryAndaz Amsterdam -Guest RelationsReport response as inappropriateThank you. We appreciate your input.This response is the subjective opinion of the management representative'
m = re.search('ago', test)
response = test[m.end():]
This is the object produced by regex: <re.Match object; span=(41, 44), match='ago'>
You can use m.start() to get the position of the first character and m.end() to get the last character.
Post a Comment for "Python: Split A String By The Position Of A Character"