How to substring a string?


Question

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 to set string two to be...

print str2  # 'Open source'

How can I acheive this using python or jython?

1
3
7/9/2013 3:28:51 PM

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'
9
12/9/2010 10:21:22 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon