Python:按字符位置分割字符串 [英] Python: split a string by the position of a character

查看:928
本文介绍了Python:按字符位置分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按单词的位置分割字符串?

How can I split a string by the position of a word?

我的数据如下:

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在哪里分割它.例如:

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

我可以使用什么函数来拆分整数? split()函数不适用于int.

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

推荐答案

您可以使用切片对字符串(和列表)进行此操作:

You can do this with strings (and lists) using slicing:

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

将导致:

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

这篇关于Python:按字符位置分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆