以Python中拆分后的包含字符串数组为例

以Python中拆分后的包含字符串数组为例,python,python-3.x,Python,Python 3.x,如果我有一些文本,比如: text= " First sentence. Second sentence. Third sentence." 在这之后,我以“.”分开: new_split = text.split('.') 我将收到:[“第一句话”、“第二句话”、“第三句话] 如果我叫它,我怎么能把第二句话都打印出来 比如: 我想知道如何获得整个“第二句话”,如果我知道在我的拆分中存在一个包含我的关键字的句子 text= " First sentence. Second sente

如果我有一些文本,比如:

 text= "  First sentence. Second sentence. Third sentence."
在这之后,我以“.”分开:

 new_split = text.split('.')
我将收到:
[“第一句话”、“第二句话”、“第三句话]

如果我叫它,我怎么能把第二句话都打印出来

比如:

我想知道如何获得整个“第二句话”,如果我知道在我的拆分中存在一个包含我的关键字的句子

text= "  First sentence. Second sentence. Third sentence."

[print(i) for i in text.split('.') if "second" in i.lower()]
哪个
打印

 Second sentence

以上是我能想到的用
来做这件事的最短方法,但你也可以用
for loop
而不是
list comp

for sentence in text.split('.'):
    if "second" in sentence.lower():
        print(sentence)
哪个
打印

 Second sentence

以上是我能想到的用
来做这件事的最短方法,但你也可以用
for loop
而不是
list comp

for sentence in text.split('.'):
    if "second" in sentence.lower():
        print(sentence)

要查找包含给定子字符串的句子列表中第一个句子的索引,请执行以下操作:

i = next(i for i, sentence in enumerate(sentences) if word in sentence)
简单Python也是如此:

for i, sentence in enumerate(sentences):
    if word in sentence:
        break
else:
    # the word is not in any of the sentences

要查找包含给定子字符串的句子列表中第一个句子的索引,请执行以下操作:

i = next(i for i, sentence in enumerate(sentences) if word in sentence)
简单Python也是如此:

for i, sentence in enumerate(sentences):
    if word in sentence:
        break
else:
    # the word is not in any of the sentences
您可以尝试以下方法:

text= "  First sentence. Second sentence. Third sentence."
new_text = [i for i in text.split('.') if "second" in i.lower()][0]
输出:

' Second sentence'
您可以尝试以下方法:

text= "  First sentence. Second sentence. Third sentence."
new_text = [i for i in text.split('.') if "second" in i.lower()][0]
输出:

' Second sentence'
试试这个:

if new_split[1] != '': 
    print(new_split[1])
试试这个:

if new_split[1] != '': 
    print(new_split[1])

请注意,它产生了
“第二句话”
,不像OP说的那样。@Jean-Françoisfare我的错,我应该仔细阅读,我会更新answer@Jean-Françoisfar Yea很抱歉,我现在已经更新了答案,正确地回答了这个问题……请注意,它产生了
“第二句话”
,与OP所说的不同,让·弗朗索瓦·法布是我的错,我应该更仔细地阅读,我会更新answer@Jean-Françoisfar Yea很抱歉,我已经更新了答案,现在可以正确回答这个问题了……在问这个问题之前,你不知道基本列表索引吗?@cᴏʟᴅsᴘᴇᴇᴅ 据我所知,O.P知道列表索引,但不知道
enumerate
if new_split[1]!='':print(new_split[1])
@Doda为什么删除你的答案并将其转换为评论?因为我不确定这是否是他想要的。在问这个问题之前,你不知道基本列表索引?@cᴏʟᴅsᴘᴇᴇᴅ 据我所知,O.P知道列表索引,但不知道
enumerate
if new_split[1]!='':print(new_split[1])
@Doda为什么删除你的答案并将其转换为评论?因为我不确定这是否是他想要的。