How to substring a string?
I have a string "MenuItem {Open source}"
.
How can I get the string Open source
from my string?
e.g.
str1 = "MenuItem {Open source}"
perform some actions t开发者_StackOverflowo set string two to be...
print str2 # 'Open source'
How can I acheive this using python or jython?
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.rsplit
rather than str.split
to make sure it splits at the right-most match):
>>> str1.rsplit('{')[1].rsplit('}')[0]
'Open source'
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
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"
.
Of course, that's assuming it's always Open Source and MenuItem...
Instead, you can use 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.
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.
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 ;)
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"!!!
精彩评论