如何在Python中将字符串从第一次出现的子字符串的索引切成第二次出现的子字符串的索引?

时间:2019-05-20 14:49:19

标签: python string slice jupyter

我正在做一项家庭作业,我必须弄清楚如何从子字符串的第一次出现的索引处开始将字符串切成该子字符串的第二次出现的索引处。问题特别是试图将字符串“并置”从第一个“ t”切成第二个“ t”,我们应该使用.find()来做到这一点,但我一直无法弄清楚。

我尝试使用WHILE创建循环以查找子字符串不同出现的索引,然后使用该索引对字符串进行切片,但是我无法使其工作。

这是到目前为止我能想到的:

long_word = "juxtaposition"
location = long_word.find("t")
start_index = location
stop_index = 0
while location != -1:
    stop_index + long_word.find("t",location + 1)
print(long_word[int(start_index),int(stop_index)])

当我运行它时,它没有显示错误消息,但也没有显示输出,为了再次编辑单元格,我必须中断内核。

4 个答案:

答案 0 :(得分:0)

我相信这将仅使用.find()方法来查找第一次和第二次出现的字符串,打印的字符串包括第一次和第二次出现:

{% load static %}
{% get_media_prefix as MEDIA_PREFIX %}
{% for Produto in list %}
    <img src="{{ MEDIA_PREFIX }}{{ Produto.foto }}"/>
{% endfor %}

输出:

enter image description here

答案 1 :(得分:0)

有上百万种方法可以解决此问题。其中一个比较丑陋但有趣的学习方法是对字符串进行切片,例如:mystring[start:stop],其中将起始点指定为第一个.find(),将终止点指定为第二个.find()。 / p>

停止点很有趣,因为您将.find()+ 1作为.find()的起点,因此它跳过了字母的第一个实例。如果需要的话,最后的+1将在输出中包含“ t”。

通常在python中会因为不必要的不​​可读而对此感到不满意,但我想我会发布它,以使您了解解决这些问题的灵活程度

long_word[long_word.find('t'):long_word.find('t',long_word.find('t')+1)+1]

输出

'taposit'

答案 2 :(得分:0)

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches


long_word = "juxtaposition"
location = "t"
locations = (list(find_all(long_word, location)))
substr = long_word[locations[0]:locations[1]+1]
print (substr)

输出:

taposit

答案 3 :(得分:0)

Python中字符串上的find方法为字符串中的索引接受第二个参数,以开始搜索。为了找到子字符串索引的第二次出现,请为find提供第二次出现的索引的索引+ 1:

def get_substring(long_word, search):
    first_occurence_idx = long_word.find(search)

    if first_occurence_idx == -1:
        return

    # for second call of `find`, provide start param so that it only searches
    # after the first occurence
    second_occurence_idx = long_word.find(search, first_occurence_idx + 1)

    if second_occurence_idx == -1:
        return

    return long_word[first_occurence_idx:second_occurence_idx + len(search)]

# example provided
assert get_substring('juxtaposition', 't') == 'taposit'

# case where search occurs once in long_word
assert get_substring('juxtaposition', 'x') is None

# case where search is not in long_word
assert get_substring('juxtaposition', 'z') is None

# case where len(search > 1) and search occurs twice
assert get_substring('juxtaposition justice', 'ju') == 'juxtaposition ju'
相关问题