Python:按字符位置拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46766530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: split a string by the position of a character
提问by Lisadk
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:
我知道find.()
函数给出了一个词的位置,我想用这个位置来告诉 Python 在哪里拆分它。例如:
splitat = test.find('ago')+3
What function can I use to split with an integer? The split()
function does not work with an int.
我可以使用什么函数来分割整数?该split()
函数不适用于 int。
回答by Jurgy
You can do this with strings (and lists) using slicing:
您可以使用切片对字符串(和列表)执行此操作:
str = "hello world!"
splitat = 4
l, r = str[:splitat], str[splitat:]
will result in:
将导致:
>>> l
hell
>>> r
o world!
回答by Oleh Rybalchenko
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:])