如何对字符串进行子串化?
我有一个字符串“MenuItem {开源}”
。
如何从我的字符串中获取字符串 Open source
?
例如,
str1 = "MenuItem {Open source}"
执行一些操作将字符串二设置为...
print str2 # 'Open source'
我如何使用 python 或 jython 实现此目的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用正则表达式获取它。
您还可以通过在
{
和}
分隔符上拆分字符串来获取它(这里我使用str.rsplit
而不是str. split
以确保它在最右侧的匹配处拆分):You can get it with a regular expression.
You can also get it by splitting the string on the
{
and}
delimiters (here I usestr.rsplit
rather thanstr.split
to make sure it splits at the right-most match):提取子字符串:Python 中的字符串可以像数组一样加下标:
s[4] = 'a'
。与 IDL 一样,索引可以用切片表示法指定,即两个索引用冒号分隔。这将返回一个包含字符index1到index2-1的子字符串。索引也可以为负数,在这种情况下它们从右侧开始计数,即-1 是最后一个字符。因此,可以像“因此在您的示例中”那样提取子字符串,您需要
str2 = str1[10:21] = "Open Source"
。当然,这是假设它始终是 Open Source 和 MenuItem...
相反,您可以使用
find
:返回 sub 在字符串中第一次出现的数字位置。如果未找到 sub,则返回 -1。
因此,您可以使用
str1.find("{")
获取第一个大括号,使用str1.find("}")
获取第二个大括号。或者在一个:
未经测试的代码中,您可能需要在某处添加+1,但理论上应该可行,或者至少让您走上正确的轨道;)
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 likeTherefore 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
:returns the numeric position of the first occurance of sub in the string. Returns -1 if sub is not found.
So you can use
str1.find("{")
to get the first brace, andstr1.find("}")
to get the second.or in one:
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 ;)
你就看到了字符串“开源”!
There you are with the string "Open source"!!!