如何在Python中分割和解析字符串?
我正在尝试在 python 中拆分此字符串: 2.7.0_bf4fda703454
我想在下划线 _
上拆分该字符串,以便我可以使用左侧的值。
I am trying to split this string in python: 2.7.0_bf4fda703454
I want to split that string on the underscore _
so that I can use the value on the left side.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
"2.7.0_bf4fda703454".split("_")
给出字符串列表:这会在每个下划线处分割字符串。如果您希望它在第一次分割后停止,请使用
"2.7.0_bf4fda703454".split("_", 1)
。如果您知道字符串包含下划线,您甚至可以将 LHS 和 RHS 解包到单独的变量中:
另一种方法是使用
partition()
。用法与上一个示例类似,只是它返回三个组件而不是两个。主要优点是,如果字符串不包含分隔符,此方法不会失败。"2.7.0_bf4fda703454".split("_")
gives a list of strings:This splits the string at every underscore. If you want it to stop after the first split, use
"2.7.0_bf4fda703454".split("_", 1)
.If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:
An alternative is to use
partition()
. The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.Python 字符串解析演练
在空格上分割字符串,获取列表,显示其类型,打印出来:
如果两个分隔符彼此相邻,则假定为空字符串: >
用下划线分割字符串并获取列表中的第 5 项:
将多个空格折叠为一个
当您不向 Python 的 split 方法传递任何参数时,文档指出:“连续的空格被视为单个分隔符,结果将不包含空字符串如果字符串有前导或尾随空格,则在开头或结尾”。
抓住你的帽子,男孩们,解析正则表达式:
正则表达式“[am]+”表示小写字母
a
到m
,出现一次或多次作为分隔符进行匹配。re
是要导入的库。或者,如果您想一次咀嚼一个项目:
Python string parsing walkthrough
Split a string on space, get a list, show its type, print it out:
If you have two delimiters next to each other, empty string is assumed:
Split a string on underscore and grab the 5th item in the list:
Collapse multiple spaces into one
When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".
Hold onto your hats boys, parse on a regular expression:
The regular expression "[a-m]+" means the lowercase letters
a
throughm
that occur one or more times are matched as a delimiter.re
is a library to be imported.Or if you want to chomp the items one at a time:
如果始终是均匀的 LHS/RHS 分割,您还可以使用字符串中内置的
partition
方法。如果找到分隔符,则返回一个 3 元组(LHS,separator, RHS)
;如果未找到分隔符,则返回(original_string, '', '')
展示:If it's always going to be an even LHS/RHS split, you can also use the
partition
method that's built into strings. It returns a 3-tuple as(LHS, separator, RHS)
if the separator is found, and(original_string, '', '')
if the separator wasn't present: