在python中拆分字符串以获取一个值? [英] split string in python to get one value?
问题描述
需要帮助,我们假设我在名为输入"的变量中有一个字符串"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屋!