특정 서브스트링 뒤에 문자열을 얻는 방법
특정 서브스트링 뒤에 문자열을 얻으려면 어떻게 해야 하나요?
예를 들어, 나는 다음에 스트링을 받고 싶다."world"
에
my_string="hello python world, I'm a beginner"
...이 경우는 다음과 같습니다.", I'm a beginner"
)
가장 쉬운 방법은 아마도 당신의 목표 단어를 분할하는 것이다.
my_string="hello python world , i'm a beginner"
print(my_string.split("world",1)[1])
split은 분할할 단어(또는 문자)를 사용하며 분할 횟수에 대한 제한(선택사항)을 지정합니다.
이 예에서는 "world"로 분할하고 분할을 1개로 제한합니다.
아무도 이 일에 대해 언급하지 않았다니 놀랍군요partition
.
def substring_after(s, delim):
return s.partition(delim)[2]
s1="hello python world, I'm a beginner"
substring_after(s1, "world")
# ", I'm a beginner"
IMHO, 이 솔루션은 @arshajii의 솔루션보다 읽기 쉽습니다.그 외에는 @arshajii가 가장 빠르다고 생각합니다.불필요한 카피나 투고를 하지 않습니다.
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
.
다음을 사용하는 경우:
>>> 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
를 사용할 수도 있습니다.제한은 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%
여기에는 딜리미터가 누락되어 있거나(최악의 경우 시나리오), 첫 번째(최적의 경우 시나리오), 또는 하위 절반, 상위 절반 또는 마지막 위치에 있는 실행당 타이밍이 표시됩니다.가장 빠른 시간은 다음과 같이 표시됩니다.[...]
그리고.<...>
최악이군
위의 표는 아래에 제시된 세 가지 옵션 모두에 대한 포괄적인 타임 트라이얼로 작성되었습니다.Python 3.7.4에서 2.9GHz Intel Core i7 및 16GB RAM을 탑재한 2017년형 15인치 Macbook Pro에서 테스트를 수행했습니다.
이 스크립트는 랜덤하게 선택된 딜리미터가 존재하는지 여부에 관계없이 랜덤한 문장을 생성하고 생성된 문장의 다른 위치에서 랜덤 순서로 테스트를 실행하고(테스트 중에 발생하는 랜덤 OS 이벤트를 고려하여 가장 공정한 결과를 생성) 결과 표를 인쇄합니다.
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=" ")
regex를 사용하여 이 작업을 수행하려면 캡처되지 않은 그룹을 사용하여 "world"라는 단어를 얻은 후 모든 것을 캡처할 수 있습니다.
(?:world).*
예제 문자열은 여기서 테스트합니다.
Python 3.에서는removeprefix
이치노
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
- 문서: https://docs.python.org/3.9/library/stdtypes.html#str.removeprefix
- 발표: https://docs.python.org/3.9/whatsnew/3.9.html
라는 패키지를 사용할 수 있습니다.substring
만 하면 .pip install substring
. 및 끝 수 시작 및 끝 문자/인디케이터만 언급하면 서브스트링을 얻을 수 있습니다.
예를 들어:
import substring
s = substring.substringByChar("abcdefghijklmnop", startChar="d", endChar="n")
print(s)
출력:
# s = defghijklmn
다음과 같은 일반적인 방법을 사용해 보십시오.
import re
my_string="hello python world , i'm a beginner"
p = re.compile("world(.*)")
print(p.findall(my_string))
# [" , i'm a beginner "]
오래된 질문이지만, 같은 시나리오에 직면했습니다만, 「낮다」라는 단어를 디밀리터로 사용해 문자열을 분할할 필요가 있었습니다.문제는, 같은 문자열에 아래아래의 단어가 있는 것이었습니다.
이 방법으로 re 모듈을 사용하여 해결했습니다.
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.'
# use re.split with regex to match the exact word
stringafterword = re.split('\\blow\\b',string)[-1]
print(stringafterword)
# ' reading is seen as positive (or bullish) for the Korean Won.'
# the generic code is:
re.split('\\bTHE_WORD_YOU_WANT\\b',string)[-1]
이것이 누군가에게 도움이 되기를 바랍니다!
언급URL : https://stackoverflow.com/questions/12572362/how-to-get-a-string-after-a-specific-substring
'programing' 카테고리의 다른 글
Debian 10 MariaDB '소켓 '/var/run/mysqld/mysqld를 통해 로컬 MySQL 서버에 연결할 수 없습니다.양말' (2)' (0) | 2022.09.19 |
---|---|
변수가 null이 아닌지 확인하는 방법 (0) | 2022.09.19 |
PHP 함수의 전역 변수 액세스 (0) | 2022.09.19 |
어떻게 조건부로의 반응 요소들에 특성을 추가하니? (0) | 2022.09.19 |
ubuntu 서버에서 pip install mariadb 오류 발생 (0) | 2022.09.19 |