簡體   English   中英

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

[英]Python: split a string by the position of a character

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

我的數據如下所示:

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。

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

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

將導致:

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

也許最簡單的解決方案是使用字符串切片:

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:])

為您提供了一個內置功能。

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():]

這是正則表達式產生的對象: <re.Match object; span=(41, 44), match='ago'>

您可以使用 m.start() 獲取第一個字符的位置,使用 m.end() 獲取最后一個字符的位置。

https://docs.python.org/3/library/re.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM