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

查看:101
本文介绍了如何在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("_")给出了字符串列表:

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天全站免登陆