在python中拆分字符串以获取一个值? [英] split string in python to get one value?

查看:486
本文介绍了在python中拆分字符串以获取一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助,我们假设我在名为输入"的变量中有一个字符串"Sam-Person"

Need help, let's assume that I have a string 'Sam-Person' in a variable called 'input'

name, kind = input.split('-')

通过上述操作,我得到了两个带有不同字符串'Sam'和'Person'的变量 有没有一种方法可以只获取第一个值名称='Sam',而无需使用额外的变量'kind',而不必使用列表? 这样做时,假设我只会得到"Sam":

By doing the above, I get two variable with different strings 'Sam' and 'Person' is there a way to only get the first value name = 'Sam' without the need of the extra variable 'kind' and without having to work with lists? When doing this, assuming that I was going to get only 'Sam':

name = input.split('-')

我得到一个列表,然后可以通过索引名称[0]或名称[1]访问值,但这不是我想要的,我只想直接将'Sam'放入变量'name' ,有没有办法做到这一点或替代分裂?

I get a list, and then I can access the values by index name[0] or name[1], but it is not what I want, I just want to directly get 'Sam' into the variable 'name', is there a way to do that or an alternative to split?

推荐答案

将第一项直接分配给变量.

Assign the first item directly to the variable.

>>> string = 'Sam-Person'
>>> name = string.split('-')[0]
>>> name
'Sam'

您可以指定maxsplit参数,因为您只想获取第一项.

You can specify maxsplit argument, because you want to get only the first item.

>>> name = string.split('-', 1)[0]

这篇关于在python中拆分字符串以获取一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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