Jak uzyskać ciąg po określonym fragmencie?

Jak mogę uzyskać ciąg znaków po określonym podłańcuchu?

Na przykład chcę uzyskać ciąg po "world" W my_string="hello python world , I'm a beginner " (który w tym przypadku jest:, I'm a beginner)

Author: Guy Avraham, 2012-09-24

9 answers

Najprostszym sposobem jest prawdopodobnie po prostu podzielić na słowo docelowe

my_string="hello python world , i'm a beginner "
print my_string.split("world",1)[1] 

Split przyjmuje słowo (lub znak) do podziału i opcjonalnie ograniczenie liczby podziałów.

W tym przykładzie podziel na "świat" i ogranicz go tylko do jednego podziału.

 448
Author: Joran Beasley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-21 16:25:47
s1 = "hello python world , i'm a beginner "
s2 = "world"

print s1[s1.index(s2) + len(s2):]

Jeśli chcesz zająć się przypadkiem, w którym s2 jest , a nie obecne w s1, Użyj s1.find(s2) w przeciwieństwie do index. Jeśli wartość zwracana tego wywołania to -1, to {[1] } nie jest w s1.

 68
Author: arshajii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-04 01:25:47

Dziwię się, że nikt o tym nie wspomniał.

def substring_after(s, delim):
    return s.partition(delim)[2]

IMHO, To rozwiązanie jest bardziej czytelne niż @arshajii 's. Poza tym uważam, że @arshajii' S jest najlepsze jako najszybsze - nie tworzy żadnych zbędnych kopii/podciągów.

 63
Author: shx2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-12 09:47:06

Chcesz użyć str.partition():

>>> my_string.partition("world")[2]
" , i'm a beginner "

Ponieważ ta opcja jest szybsza niż alternatywy.

Zauważ, że to tworzy pusty łańcuch, jeśli nie ma ogranicznika:

>>> my_string.partition("Monty")[2]  # delimiter missing
''

Jeśli chcesz mieć oryginalny ciąg znaków, sprawdź, czy wartość second zwrócona z str.partition() jest niepusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_pusta_]}

prefix, success, result = my_string.partition(delimiter)
if not success: result = prefix

Możesz również użyć str.split() z limitem 1:

>>> my_string.split("world", 1)[-1]
" , i'm a beginner "
>>> my_string.split("Monty", 1)[-1]  # delimiter missing
"hello python world , i'm a beginner "

Jednak ta opcja jest wolniejsza. Na w najlepszym przypadku str.partition() jest łatwo o o 15% szybszy w porównaniu do str.split():

                                missing        first         lower         upper          last
      str.partition(...)[2]:  [3.745 usec]  [0.434 usec]  [1.533 usec]  <3.543 usec>  [4.075 usec]
str.partition(...) and test:   3.793 usec    0.445 usec    1.597 usec    3.208 usec    4.170 usec
      str.split(..., 1)[-1]:  <3.817 usec>  <0.518 usec>  <1.632 usec>  [3.191 usec]  <4.173 usec>
            % best vs worst:         1.9%         16.2%          6.1%          9.9%          2.3%

Pokazuje timingi Na wykonanie z wejściami tutaj ogranicznik jest albo brakujący( najgorszy scenariusz), umieszczony jako pierwszy( najlepszy scenariusz), albo w dolnej połowie, górnej połowie lub na ostatniej pozycji. Najszybszy czas oznaczany jest symbolem [...], a <...> oznacza najgorszy.

Powyższa tabela jest sporządzona przez kompleksową próbę czasową dla wszystkich trzech opcji, wyprodukowanych poniżej. Prowadziłem testy Pythona 3.7.4 na modelu 2017 15 " Macbook Pro z Intel Core i7 2,9 GHz i 16 GB PAMIĘCI ram.

Ten skrypt generuje losowe zdania z i bez losowo wybranego ogranicznika obecnego, a jeśli jest obecny, w różnych pozycjach generowanego zdania, uruchamia testy w losowej kolejności z powtórzeniami (tworząc najpiękniejsze wyniki uwzględniające losowe zdarzenia OS zachodzące podczas testowania), a następnie wyświetla tabelę wyników:

import random
from itertools import product
from operator import itemgetter
from pathlib import Path
from timeit import Timer

setup = "from __main__ import sentence as s, delimiter as d"
tests = {
    "str.partition(...)[2]": "r = s.partition(d)[2]",
    "str.partition(...) and test": (
        "prefix, success, result = s.partition(d)\n"
        "if not success: result = prefix"
    ),
    "str.split(..., 1)[-1]": "r = s.split(d, 1)[-1]",
}

placement = "missing first lower upper last".split()
delimiter_count = 3

wordfile = Path("/usr/dict/words")  # Linux
if not wordfile.exists():
    # macos
    wordfile = Path("/usr/share/dict/words")
words = [w.strip() for w in wordfile.open()]

def gen_sentence(delimiter, where="missing", l=1000):
    """Generate a random sentence of length l

    The delimiter is incorporated according to the value of where:

    "missing": no delimiter
    "first":   delimiter is the first word
    "lower":   delimiter is present in the first half
    "upper":   delimiter is present in the second half
    "last":    delimiter is the last word

    """
    possible = [w for w in words if delimiter not in w]
    sentence = random.choices(possible, k=l)
    half = l // 2
    if where == "first":
        # best case, at the start
        sentence[0] = delimiter
    elif where == "lower":
        # lower half
        sentence[random.randrange(1, half)] = delimiter
    elif where == "upper":
        sentence[random.randrange(half, l)] = delimiter
    elif where == "last":
        sentence[-1] = delimiter
    # else: worst case, no delimiter

    return " ".join(sentence)

delimiters = random.choices(words, k=delimiter_count)
timings = {}
sentences = [
    # where, delimiter, sentence
    (w, d, gen_sentence(d, w)) for d, w in product(delimiters, placement)
]
test_mix = [
    # label, test, where, delimiter sentence
    (*t, *s) for t, s in product(tests.items(), sentences)
]
random.shuffle(test_mix)

for i, (label, test, where, delimiter, sentence) in enumerate(test_mix, 1):
    print(f"\rRunning timed tests, {i:2d}/{len(test_mix)}", end="")
    t = Timer(test, setup)
    number, _ = t.autorange()
    results = t.repeat(5, number)
    # best time for this specific random sentence and placement
    timings.setdefault(
        label, {}
    ).setdefault(
        where, []
    ).append(min(dt / number for dt in results))

print()

scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
width = max(map(len, timings))
rows = []
bestrow = dict.fromkeys(placement, (float("inf"), None))
worstrow = dict.fromkeys(placement, (float("-inf"), None))

for row, label in enumerate(tests):
    columns = []
    worst = float("-inf")
    for p in placement:
        timing = min(timings[label][p])
        if timing < bestrow[p][0]:
            bestrow[p] = (timing, row)
        if timing > worstrow[p][0]:
            worstrow[p] = (timing, row)
        worst = max(timing, worst)
        columns.append(timing)

    scale, unit = next((s, u) for s, u in scales if worst >= s)
    rows.append(
        [f"{label:>{width}}:", *(f" {c / scale:.3f} {unit} " for c in columns)]
    )

colwidth = max(len(c) for r in rows for c in r[1:])
print(' ' * (width + 1), *(p.center(colwidth) for p in placement), sep="  ")
for r, row in enumerate(rows):
    for c, p in enumerate(placement, 1):
        if bestrow[p][1] == r:
            row[c] = f"[{row[c][1:-1]}]"
        elif worstrow[p][1] == r:
            row[c] = f"<{row[c][1:-1]}>"
    print(*row, sep="  ")

percentages = []
for p in placement:
    best, worst = bestrow[p][0], worstrow[p][0]
    ratio = ((worst - best) / worst)
    percentages.append(f"{ratio:{colwidth - 1}.1%} ")

print("% best vs worst:".rjust(width + 1), *percentages, sep="  ")
 30
Author: Martijn Pieters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-16 19:24:29

Jeśli chcesz to zrobić używając regex, możesz po prostu użyć grupy nie przechwytywającej , aby uzyskać słowo "świat", a następnie pobrać wszystko po, tak

(?:world).*

Przykładowy ciąg jest testowany tutaj

 20
Author: Tadgh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-18 20:17:52

Możesz użyć pakietu o nazwie substring. Wystarczy zainstalować za pomocą polecenia pip install substring. Podłańcuch można uzyskać po prostu podając znaki/indeksy początku i końca.

Na przykład:

import substring
s = substring.substringByChar("abcdefghijklmnop", startChar="d", endChar="n")
print(s)

Wyjście:

# s = defghijklmn
 5
Author: Sriram Veturi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-20 11:54:09

Wypróbuj to ogólne podejście:

import re
my_string="hello python world , i'm a beginner "
p = re.compile("world(.*)")
print (p.findall(my_string))

#[" , i'm a beginner "]
 4
Author: Hadij,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-27 23:36:56

W Pythonie 3.9 dodawana jest nowa metoda removeprefix:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
 4
Author: gntskn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-10 15:21:25

To stare pytanie, ale stanąłem przed tym samym scenariuszem, muszę podzielić ciąg używając jako demiliter słowa "niski" problem dla mnie było to, że mam w tym samym ciągu słowo poniżej i niżej.

Rozwiązałem to używając modułu re w ten sposób

import re

string = '...below...as higher prices mean lower demand to be expected. Generally, a high reading is seen as negative (or bearish), while a low reading is seen as positive (or bullish) for the Korean Won.'

Użyj re.podziel za pomocą regex, aby dopasować dokładne słowo

stringafterword = re.split('\\blow\\b',string)[-1]
print(stringafterword)
' reading is seen as positive (or bullish) for the Korean Won.'

Kod ogólny to:

re.split('\\bTHE_WORD_YOU_WANT\\b',string)[-1]
Mam nadzieję, że to może komuś pomóc!
 3
Author: Leonardo Hermoso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-13 03:15:16