如何在 Python 中拆分和解析字符串? [英] How can I split and parse a string in Python?

查看:34
本文介绍了如何在 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.

推荐答案

"2.7.0_bf4fda703454".split("_") 给出一个字符串列表:

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

这会在每个下划线处拆分字符串.如果您希望它在第一次拆分后停止,请使用 "2.7.0_bf4fda703454".split("_", 1).

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

如果您知道字符串包含下划线,您甚至可以将 LHS 和 RHS 解包为单独的变量:

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

另一种方法是使用 partition().用法与上一个示例类似,不同之处在于它返回三个组件而不是两个.主要优点是,如果字符串不包含分隔符,则此方法不会失败.

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 中拆分和解析字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆