एक विशिष्ट विकल्प के बाद एक स्ट्रिंग कैसे प्राप्त करें?


226

विशिष्ट प्रतिस्थापन के बाद मुझे एक स्ट्रिंग कैसे मिल सकती है?

उदाहरण के लिए, मैं के बाद स्ट्रिंग प्राप्त करना चाहते हैं "world"मेंmy_string="hello python world , i'm a beginner "

जवाबों:


399

सबसे आसान तरीका शायद अपने लक्ष्य शब्द पर विभाजित करना है

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

विभाजन शब्द (या वर्ण) को विभाजित करने के लिए लेता है और वैकल्पिक रूप से विभाजन की संख्या तक सीमित करता है।

इस उदाहरण में "दुनिया" पर विभाजित करें और इसे केवल एक विभाजन तक सीमित करें।


अगर मुझे किसी पाठ को 'निम्न' शब्द के साथ विभाजित करने की आवश्यकता है और उसमें पहले वाला शब्द कम है, तो यह काम नहीं करेगा!
लियोनार्डो हर्मोसो

1
आप सरलता से 2xtarget.split('lower',1)[-1].split('low',1)[-1]
जोरान बिसले

क्या होगा अगर वाक्य "हेलो पायथन मेगावर्ड वर्ल्ड, मैं एक शुरुआती हूं"। मैं इसे पूरे शब्द को कैसे देख सकता हूं और दूसरे का हिस्सा नहीं 'मेगावर्ड' के रूप में? धन्यवाद
pbou

1
तो स्ट्रिंग आप खोज "दुनिया" ... या उपयोग regex शब्द boundrys के लिए है
Joran बीस्ले

6
my_string.partition("world")[-1](या ...[2]) तेज है।
मार्टिन पीटर्स

66
s1 = "hello python world , i'm a beginner "
s2 = "world"

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

यदि आप उस मामले से निपटना चाहते हैं जहां s2मौजूद नहीं है s1, तो s1.find(s2)विरोध के रूप में उपयोग करें index। यदि उस कॉल का रिटर्न मान है -1, तो अंदर s2नहीं है s1


आपको अलग-अलग आईडी मिलते हैं (जो कि कई हजार से अलग हो जाते हैं) ... मुझे यकीन नहीं है कि आप इस के साथ गैर-जरूरी उप-निर्माण नहीं करेंगे
जोरान बिसले

@JoranBeasley, हम केवल इंडेक्स (), लेन () और स्लाइस कहते हैं। अनुक्रमण बनाने के लिए कोई कारण नहीं है () और लेन () के लिए, और यदि वे करते हैं (मुझे विश्वास करना कठिन लगता है), तो यह सिर्फ एक अनावश्यक कार्यान्वयन विवरण है। स्लाइस के लिए एक ही - इसके लिए कोई कारण नहीं है कि जो एक लौटाया गया है उसके अलावा सबस्ट्रिंग बनाए।
shx2

@ shx2print( s1[s1.index(s2) + len(s2):] is s1[s1.index(s2) + len(s2):])
Joran बीस्ले

@JoranBeasley आप इस स्निपेट के साथ क्या करने की कोशिश कर रहे हैं? कई कॉल पर विभिन्न वस्तुओं को लौटाया जाता है? "अनावश्यक सबस्ट्रिंग" से मेरा मतलब है कि लौटे हुए पदार्थों के अलावा अन्य सब्सट्रिंग्स, यानी सब्सट्रिंग्स जो परिणाम प्राप्त करने के लिए बनाने के लिए आवश्यक नहीं हैं।
shx2

57

मुझे आश्चर्य है कि किसी ने उल्लेख नहीं किया partition

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

IMHO, यह समाधान @ arshajii की तुलना में अधिक पठनीय है। इसके अलावा, मुझे लगता है कि @ अर्शजी का सबसे तेज़ होने के लिए सबसे अच्छा है - यह किसी भी अनावश्यक प्रतियां / सबस्ट्रिंग नहीं बनाता है।


2
यह एक अच्छा समाधान है, और इस मामले को संभालता है जहां सबस्ट्रिंग बेस स्ट्रिंग का एक हिस्सा नहीं है।
मटका

आपको अलग-अलग आईडी मिलते हैं (जो कि कई हजार से अलग हो जाते हैं) ... मुझे यकीन नहीं है कि आप इस के साथ अप्राकृतिक सब्सट्रिंग्स न बनाएं (और इसे ठीक से प्रोफाइल करने के लिए बहुत आलसी भी हों)
जॉरन बीस्ले

1
@JoranBeasley, यह स्पष्ट रूप से करता है अनावश्यक substings पैदा करते हैं। मुझे लगता है कि आपने मेरे जवाब को गलत बताया।
shx2

(तो अर्शी का मुझे लगता है ...)
जोरन बेस्ले

3
इसके अलावा, यह तेजी से है str.split(..., 1)
मार्टिन पीटर्स

20

आप उपयोग करना चाहते हैं str.partition():

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

क्योंकि यह विकल्प विकल्पों की तुलना में तेज है

ध्यान दें कि यह एक खाली स्ट्रिंग पैदा करता है यदि सीमांकक गायब है:

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

यदि आप मूल स्ट्रिंग रखना चाहते हैं, तो परीक्षण करें कि यदि दूसरा मान लौटाया गया str.partition()तो गैर-रिक्त है:

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

आप str.split()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 "

हालाँकि, यह विकल्प धीमा है । सर्वोत्तम स्थिति के परिदृश्य के लिए, str.partition()इसकी तुलना में आसानी से लगभग 15% तेज है 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%

यह इनपुट के साथ प्रति निष्पादन समय दिखाता है यहां सीमांकक या तो गायब है (सबसे खराब स्थिति), पहले रखा गया (सबसे अच्छा मामला परिदृश्य), या निचले आधे, ऊपरी आधे या अंतिम स्थिति में। सबसे तेज समय के साथ चिह्नित है [...]और <...>निशान सबसे खराब।

उपरोक्त तालिका सभी तीन विकल्पों के लिए एक व्यापक समय परीक्षण द्वारा निर्मित है, नीचे निर्मित है। मैंने 2017 के मॉडल 15 "मैकबुक प्रो पर 2.9 गीगाहर्ट्ज इंटेल कोर आई 7 और 16 जीबी रैम के साथ पायथन 3.7.4 पर परीक्षण चलाया।

यह स्क्रिप्ट बेतरतीब ढंग से चुने गए सीमांकक के साथ और बिना यादृच्छिक वाक्य उत्पन्न करता है, और यदि मौजूद है, तो उत्पन्न वाक्य में विभिन्न पदों पर, दोहराव के साथ यादृच्छिक क्रम में परीक्षण चलाता है (परीक्षण के दौरान होने वाले यादृच्छिक ओएस घटनाओं के लिए सबसे अच्छा परिणाम लेखांकन), और फिर परिणामों की एक तालिका प्रिंट करता है:

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="  ")

बहुत बढ़िया जवाब! विशेष रूप से क्योंकि आप वास्तविक कारण प्रदान करते हैं यह बेहतर है: पी
जोरन बेस्ले

18

यदि आप रेगेक्स का उपयोग करके ऐसा करना चाहते हैं, तो आप " नॉन-कैप्चरिंग ग्रुप " का उपयोग कर सकते हैं, शब्द "दुनिया" पाने के लिए और फिर सब कुछ हड़पने के बाद, जैसे

(?:world).*

उदाहरण स्ट्रिंग का यहाँ परीक्षण किया गया है


28
कुछ लोग जब समस्या का सामना करते हैं तो सोचते हैं "मुझे पता है, बीमार एक नियमित अभिव्यक्ति का उपयोग करते हैं।" ... अब आपको 2 समस्याएँ हैं ...
जोरन बेस्ले

2
हाहा, मेरी गलती, मुझे लगा कि यह रेगेक्स को टैग किया गया था इसलिए मैंने रेगेक्स जवाब देने की कोशिश की। ओह, यह अब वहाँ है।
ताडग

1
यह सब अच्छा है ... यह निश्चित रूप से इस बिल्ली की त्वचा का एक तरीका है ... हालांकि इस समस्या के लिए overkill (imho)
जोरन Beasley

गैर-कैप्चरिंग समूह लिंक अब सही चीज़ की ओर इशारा नहीं करता है।
अपार्टेक्सक्स

1
रुचि रखने वालों के लिए। यहाँ पूर्ण कोड हैresult = re.search(r"(?:world)(.*)", "hello python world , i'm a beginner ").group(1)
रादु जूल

5

आप "प्रतिस्थापन" नामक इस पैकेज का उपयोग कर सकते हैं। बस टाइप करें "पिप इंस्टॉल सबस्ट्रिंग"। आप प्रारंभ और समाप्ति वर्णों / सूचकांकों का उल्लेख करके सबस्ट्रिंग प्राप्त कर सकते हैं।

उदाहरण के लिए:

import substring

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

print(s)

आउटपुट:

s = defghijklmn


3

यह एक पुराना प्रश्न है, लेकिन मुझे एक ही परिदृश्य का सामना करना पड़ा, मुझे "कम" शब्द का उपयोग करते हुए स्ट्रिंग को विभाजित करने की आवश्यकता है मेरे लिए समस्या यह थी कि मेरे पास एक ही स्ट्रिंग में नीचे और नीचे का शब्द है।

मैंने इसे पुनः मॉड्यूल का उपयोग करके इस तरह से हल किया

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.'

सटीक शब्द से मिलान करने के लिए regex के साथ re.split का उपयोग करें

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

सामान्य कोड है:

re.split('\\bTHE_WORD_YOU_WANT\\b',string)[-1]

आशा है कि यह किसी की मदद कर सकता है!


1
शायद आप भी इस्तेमाल कर सकते हैं string.partition(" low ")[2]:? (दोनों तरफ रिक्त स्थान पर ध्यान देंlow
माउंट देव

1

इस सामान्य दृष्टिकोण का प्रयास करें:

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

#[" , i'm a beginner "]

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.