本文介绍了在两个子字符串之间查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在两个子字符串之间找到一个字符串 ('123STRINGabc' -> 'STRING')?

我现在的方法是这样的:

>>>开始 = 'asdf = 5;'>>>结束 = '123jasd'>>>s = 'asdf = 5;iwantthis123jasd'>>>打印((s.split(start))[1].split(end)[0])我要这个

然而,这似乎非常低效且不符合 Python 风格.有什么更好的方法来做这样的事情?

忘了说:该字符串可能不会以 startend 开头和结尾.它们前后可能有更多字符.

解决方案
import res = 'asdf = 5;iwantthis123jasd'结果 = re.search('asdf=5;(.*)123jasd', s)打印(结果.组(1))

How do I find a string between two substrings ('123STRINGabc' -> 'STRING')?

My current method is like this:

>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis

However, this seems very inefficient and un-pythonic. What is a better way to do something like this?

Forgot to mention:The string might not start and end with start and end. They may have more characters before and after.

解决方案
import re

s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))

这篇关于在两个子字符串之间查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 13:29