जवाबों:
सबसे आसान तरीका शायद अपने लक्ष्य शब्द पर विभाजित करना है
my_string="hello python world , i'm a beginner "
print my_string.split("world",1)[1]
विभाजन शब्द (या वर्ण) को विभाजित करने के लिए लेता है और वैकल्पिक रूप से विभाजन की संख्या तक सीमित करता है।
इस उदाहरण में "दुनिया" पर विभाजित करें और इसे केवल एक विभाजन तक सीमित करें।
target.split('lower',1)[-1].split('low',1)[-1]
my_string.partition("world")[-1](या ...[2]) तेज है।
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।
print( s1[s1.index(s2) + len(s2):] is s1[s1.index(s2) + len(s2):])
मुझे आश्चर्य है कि किसी ने उल्लेख नहीं किया partition।
def substring_after(s, delim):
return s.partition(delim)[2]
IMHO, यह समाधान @ arshajii की तुलना में अधिक पठनीय है। इसके अलावा, मुझे लगता है कि @ अर्शजी का सबसे तेज़ होने के लिए सबसे अच्छा है - यह किसी भी अनावश्यक प्रतियां / सबस्ट्रिंग नहीं बनाता है।
str.split(..., 1)।
आप उपयोग करना चाहते हैं 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=" ")
यदि आप रेगेक्स का उपयोग करके ऐसा करना चाहते हैं, तो आप " नॉन-कैप्चरिंग ग्रुप " का उपयोग कर सकते हैं, शब्द "दुनिया" पाने के लिए और फिर सब कुछ हड़पने के बाद, जैसे
(?:world).*
result = re.search(r"(?:world)(.*)", "hello python world , i'm a beginner ").group(1)
आप "प्रतिस्थापन" नामक इस पैकेज का उपयोग कर सकते हैं। बस टाइप करें "पिप इंस्टॉल सबस्ट्रिंग"। आप प्रारंभ और समाप्ति वर्णों / सूचकांकों का उल्लेख करके सबस्ट्रिंग प्राप्त कर सकते हैं।
उदाहरण के लिए:
import substring
s = substring.substringByChar("abcdefghijklmnop", startChar="d", endChar="n")
print(s)
आउटपुट:
यह एक पुराना प्रश्न है, लेकिन मुझे एक ही परिदृश्य का सामना करना पड़ा, मुझे "कम" शब्द का उपयोग करते हुए स्ट्रिंग को विभाजित करने की आवश्यकता है मेरे लिए समस्या यह थी कि मेरे पास एक ही स्ट्रिंग में नीचे और नीचे का शब्द है।
मैंने इसे पुनः मॉड्यूल का उपयोग करके इस तरह से हल किया
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]
आशा है कि यह किसी की मदद कर सकता है!
string.partition(" low ")[2]:? (दोनों तरफ रिक्त स्थान पर ध्यान देंlow
पायथन 3.9 में, एक नई removeprefixविधि जोड़ी जा रही है:
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'