Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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'

I need this output:

responder = 'annamarypeterson, Guest relations Manager'
date = 'Responded 1 week ago'
response = 'Dear ....' #without 'This response is the subjective opinion of the management representative'

I know that the find.() function gives the position of a word, and I want to use this position to tell Python where to split it. For example:

splitat = test.find('ago')+3

What function can I use to split with an integer? The split() function does not work with an int.

like image 449
Lisadk Avatar asked Oct 16 '17 09:10

Lisadk


People also ask

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you split a string after a certain number of characters Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

How do I read a position from a string in Python?

Method 1: Get the position of a character in Python using rfind() Python String rfind() method returns the highest index of the substring if found in the given string. If not found then it returns -1.


1 Answers

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!
like image 66
Jurgy Avatar answered Oct 28 '22 05:10

Jurgy