当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How can I separate two separated words in a variable?

问题描述:

I have a variable that contains two words separated by a space, and I want to split it into two variables, one for each word. How would I do this?

As an example, my string would be hello there and I want to split it into the variables word1 and word2.

网友答案:
s = 'hello there'

word1, word2 = s.split()

will do this for you. E.g.,

In [63]: s = 'hello there'
In [64]: word1, word2 = s.split()
In [65]: print word1
hello
In [66]: print word2
there

split() is quite versatile, you can also specify other characters to split on. For more information on split() see http://docs.python.org/library/stdtypes.html?highlight=split#str.split

网友答案:

You should use string.split(s[, sep[, maxsplit]]):

s = "hello world"
word1, word2 = s.split(' ', 1)

It splits a string into a list by the char you provide as an argument. Default is a space, but I'm using it as a parameter just to make it clearer.

You can also provide the maxsplit argument and make sure the string gets splitted no more than maxsplit times (like in our string - we must have exatly one split, because we're inserting the splitted words into excatly two variables.).

网友答案:
word1, word2 = 'hello there'.split()
分享给朋友:
您可能感兴趣的文章:
随机阅读: