简体   繁体   English

如何在空格分隔字符串?

[英]How to split string where spaces are?

I want to split string where the spaces are, and put it into an array. 我想在空格处拆分字符串,然后将其放入数组中。 For example, if the str is "foo bar asdf" I want the array to be ["foo", "bar", "asdf"]. 例如,如果str是“ foo bar asdf”,我希望数组为[“ foo”,“ bar”,“ asdf”]。 I know you can easily do that like so: 我知道您可以轻松地这样做:

str = raw_input("Enter String")

cstr = ""
for char in str:
    if char == " ":
        print cstr
    else:
        cstr = cstr + char

But that outputs only the first word until the space, and it is quite bulky for something so simple. 但这只会输出第一个单词,直到空格为止。 How can I do this simply? 我该如何简单地做到这一点?

This is what the split method on strings is for: 这是针对字符串的split方法的用途:

>>> "foo bar asdf".split(' ')
['foo', 'bar', 'asdf']

The argument is the string to split on, or you can just do .split() without an argument to split on any whitespace. 参数是要分割的字符串,或者您可以执行.split()而无需在任何空格上分割的参数。

I think you're looking for: http://docs.python.org/library/stdtypes.html?highlight=split#str.split 我认为您正在寻找: http : //docs.python.org/library/stdtypes.html?highlight=split#str.split

Usage in your case would be something like: 在您的情况下,用法将类似于:

 for cstr in mystr.split(' '):  #renamed 'str' to 'mystr'
     print cstr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM