python - 打印字符串中多次出现的情况

标签 python string if-statement find-occurrences

我正在尝试编写一个函数,其中输入具有在字符串中多次出现的关键字,并且将打印关键字之后在它们之间有双引号的内容。本质上...

Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness' 

Output= someonehelpmepls 

itonlygivesmeoneinsteadofmultiple 

如果可以将输出作为自己的线路那就更好了。

这是我到目前为止所拥有的:

def getEm(s): 

    h = s.find('keyword') 

    if h == -1 
       return -1 

    else: 
       begin = s.find('"',h) 
       end = s.find('"', begin+1) 
       result = s[begin +1:end] 
    print (result)

请不要建议导入。我不知道该怎么做,也不知道它是什么,我是初学者。

最佳答案

让我们看一些示例输入:

>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'

我认为示例输入中缺少一个 ",因此我添加了它。

据我了解,您想要获取单词 keyword 后面的双引号中的字符串。如果是这样,那么:

def get_quoted_after_keyword(input):
    results = []
    split_by_keyword = input.split('keyword')
    # you said no results before the keyword
    for s in split_by_keyword[1:]:
        split_by_quote = s.split('"')
        if len(split_by_quote) > 1:
            # assuming you want exactly one quoted result per keyword
            results.append(split_by_quote[1])
    return results

>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple

它是如何工作的

让我们看第一部分:

>>> Input.split('keyword')
['alkfjjie',
 ' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
 '"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']

通过在关键字上拆分输入,在本例中我们得到了三个字符串。倒数第二个字符串是单词 keyword 后面的所有字符串。为了获取没有第一个字符串的字符串,我们使用下标:

>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
 '"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']

现在,我们的下一个任务是获取这些字符串中双引号中的部分。为此,我们将每个字符串拆分为 "。第二个字符串(编号为 1)将是双引号中的字符串。作为一个更简单的示例,让我们获取这些字符串:

>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']

接下来,我们将这两个步骤放在一起:

>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']

我们现在有了我们想要的字符串。最后一步是将它们很好地打印出来,每行一个:

>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple

限制:此方法假设关键字永远不会出现在双引号字符串内。

关于python - 打印字符串中多次出现的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671016/

相关文章:

python - 在Python 2.6.6中使用pyopengl遇到麻烦

python - 根据字典 : issue passing pandas dataframe 创建 altair 图表

c++ - std::stringstream 从字符串中读取 int 和字符串

python - 一列中每次出现的值在另一列中的总和

java - String.replaceAll 替换所有不在模式中的字符

string - 在第 n 个参数之后获取所有参数并在 bash 中将它们连接在一起

javascript - 触摸事件jQuery函数详解

c++ - 评估 IF 条件的最有效方法是什么?

我们可以在 if 语句中赋值吗?

python - 使用 pandas 建立索引的最佳实践