如何通过起始和结束字符选择字符串?

0 投票
4 回答
1922 浏览
提问于 2025-04-18 23:49

我想知道如何在Python中根据起始和结束点选择一个字符串。

比如这个字符串:

Evelin said, "Hi Dude! How are you?" and no one cared!!

或者类似这样的:

Jane said *aww! thats cute, we must try it!* John replied, "Okay!, but not now!!"

我想写一个函数,能够从 " " 中选择文本,而不是通过计算索引来选择,
而是直接从字符到字符地选择文本。

比如 "Hi Dude! How are you?""Okay!, but not now!!"

那么我该怎么做呢?有没有内置的函数可以用?

我知道Python有一个内置函数可以获取给定字符的索引。

比如,

find("something") 会返回给定字符串在字符串中的索引。

或者需要遍历整个字符串吗?

我刚开始学习Python,抱歉问这样的小问题。Python 2或3都可以!!非常感谢!!

更新:

感谢大家的回答,作为一个初学者,我想用内置的 split() 函数 quotes = string.split('"')[1::2],因为这样简单。谢谢大家,爱你们! :)

4 个回答

0

str.index(str2) 是用来找出 str2 在 str 里面的位置... 这是最简单的方法!

a = 'Evelin said, "Hi Dude! How are you?" and no one cared!!'
print a[1+a.index("\""):1+a.index("\"")+a[a.index("\"")+1:].index("\"")]

或者像 Scorpion_God 提到的,你可以简单地使用单引号,如下所示

print a[1+a.index('"'):1+a.index('"')+a[a.index('"')+1:].index('"')]

这样会得到:

Hi Dude! How are you?

引号不会被包含在内!!!

0

要从字符串中提取子串,最简单的方法就是根据特定字符进行分割。可以使用str.partition()str.rpartition()这两个方法,它们可以有效地在给定字符串的第一个或最后一个出现位置进行分割。

extracted = inputstring.partition('"')[-1].rpartition('"')[0]

通过从字符串的开始和结束进行分割,你可以得到尽可能大的子串,同时保留其中的引号。

示例:

>>> inputstring = 'Evelin said, "Hi Dude! How are you?" and no one cared!!'
>>> inputstring.partition('"')
('Evelin said, ', '"', 'Hi Dude! How are you?" and no one cared!!')
>>> inputstring.rpartition('"')
('Evelin said, "Hi Dude! How are you?', '"', ' and no one cared!!')
>>> inputstring.partition('"')[-1].rpartition('"')[0]
'Hi Dude! How are you?'
1

当然可以!请看下面的内容:

在编程中,有时候我们需要让程序在特定的条件下执行某些操作。比如说,当用户点击一个按钮时,我们希望程序能做出反应。这种情况下,我们就会用到“事件监听器”。

事件监听器就像一个守卫,它一直在关注某个特定的事件,比如鼠标点击、键盘输入等。当这个事件发生时,守卫会立刻通知程序去执行相应的操作。

简单来说,事件监听器就是让程序能够“听到”用户的操作,并根据这些操作做出反应。这样,程序就变得更加互动和智能了。

希望这个解释能帮助你理解事件监听器的基本概念!

txt='''\
Evelin said, "Hi Dude! How are you?" and no one cared!!
Jane said *aww! thats cute, we must try it!* John replied, "Okay!, but not now!!"'''

import re

print re.findall(r'"([^"]+)"', txt)
# ['Hi Dude! How are you?', 'Okay!, but not now!!']
0

如果你不想用 str.index(),可以使用正则表达式

import re

quotes = re.findall('"([^"]*)"', string)

你还可以很简单地扩展这个方法,从你的字符串中提取其他信息。

另外:

quotes = string.split('"')[1::2]

如果你选择使用 str.index()

first = string.index('"')
second = string.index('"', first+1)
quote = string[first+1:second]

撰写回答