Python:按字符的位置拆分字符串

时间:2017-10-16 09:01:13

标签: python string split find

如何按字符的位置拆分字符串?

我的数据如下:

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'

我需要这个输出:

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

我知道find.()函数给出了一个单词的位置,我想用这个位置来告诉Python在哪里拆分它。例如:

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

我可以用什么函数来分割整数? split()函数不适用于int。

2 个答案:

答案 0 :(得分:6)

您可以使用切片来完成字符串(和列表):

str = "hello world!"
splitat = 4
l, r = str[:splitat], str[splitat:]

将导致:

>>> l
hell
>>> r
o world!

答案 1 :(得分:2)

也许最简单的解决方案是使用字符串切片:

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:])
相关问题