Python 如何对字符串进行子串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4397069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to substring a string?
提问by Colin
I have a string "MenuItem {Open source}".
我有一个字符串"MenuItem {Open source}"。
How can I get the string Open sourcefrom my string?
如何Open source从我的字符串中获取字符串?
e.g.
例如
str1 = "MenuItem {Open source}"
perform some actions to set string two to be...
执行一些操作以将字符串 2 设置为...
print str2 # 'Open source'
How can I acheive this using python or jython?
我如何使用 python 或 jython 实现这一目标?
回答by Chris Morgan
You can get it with a regular expression.
你可以用正则表达式得到它。
>>> import re
>>> str1 = "MenuItem {Open source}"
>>> re.search(r'{(.*)}', str1).group(1)
'Open source'
You can also get it by splitting the string on the {and }delimiters (here I use str.rsplitrather than str.splitto make sure it splits at the right-most match):
您还可以通过在{和}分隔符上拆分字符串来获取它(这里我使用str.rsplit而不是str.split确保它在最右边的匹配处拆分):
>>> str1.rsplit('{')[1].rsplit('}')[0]
'Open source'
回答by Mark Mayo
Extracting substrings: Strings in Python can be subscripted just like an array: s[4] = 'a'. Like in IDL, indices can be specified with slice notation i.e., two indices separated by a colon. This will return a substring containing characters index1 through index2-1. Indices can also be negative, in which case they count from the right, i.e. -1 is the last character. Thus substrings can be extracted like
提取子字符串:Python 中的字符串可以像数组一样下标:s[4] = 'a'。就像在 IDL 中一样,索引可以用切片符号指定,即两个索引用冒号分隔。这将返回一个包含字符 index1 到 index2-1 的子字符串。索引也可以是负数,在这种情况下,它们从右边开始计数,即 -1 是最后一个字符。因此子串可以像
s = "Go Gators! Come on Gators!"
x = s[3:9] #x = "Gators"
x = s[:2] #x = "Go"
x = s[19:] #x = "Gators!"
x = s[-7:-2] #x = "Gator"
Therefore in your examplel, you'll need str2 = str1[10:21] = "Open Source".
因此,在您的示例中,您将需要str2 = str1[10:21] = "Open Source".
Of course, that's assuming it's always Open Source and MenuItem...
当然,这是假设它始终是开源和 MenuItem ......
Instead, you can use find:
相反,您可以使用find:
int find(sub [,start[,end]])
returns the numeric position of the first occurance of sub in the string. Returns -1 if sub is not found.
返回字符串中第一次出现 sub 的数字位置。如果未找到 sub 则返回 -1。
x = s.find("Gator") #x = 3
x = s.find("gator") #x = -1
So you can use str1.find("{")to get the first brace, and str1.find("}")to get the second.
所以你可以用str1.find("{")来获得第一个大括号,并str1.find("}")获得第二个。
or in one:
或其中之一:
str2 = str1[str1.find("{"):str1.find("}")]
untested code, you may need to add a +1 somewhere, but in theory that should work, or at least get you on the right track ;)
未经测试的代码,您可能需要在某处添加 +1,但理论上应该可行,或者至少让您走上正轨;)
回答by Divyarishi
var1 = "MenuItem {Open source}"
var2 = var1.find('{')
var3 = var1.find('}')
ans = var1[var2+1: var3]
print ans
There you are with the string "Open source"!!!
那里有字符串“开源”!!!

