python find substrings based on a delimiter

后端 未结 4 1913
离开以前
离开以前 2021-01-17 17:54

I am new to Python, so I might be missing something simple.

I am given an example:

 string = \"The , world , is , a , happy , place \" 
4条回答
  •  半阙折子戏
    2021-01-17 18:19

    Strings have a split() method for this. It returns a list:

    >>> string = "The , world , is , a , happy , place "
    >>> string.split(' , ')
    ['The', 'world', 'is', 'a', 'happy', 'place ']
    

    As you can see, there is a trailing space on the last string. A nicer way to split this kind of string would be this:

    >>> [substring.strip() for substring in string.split(',')]
    ['The', 'world', 'is', 'a', 'happy', 'place']
    

    .strip() strips whitespace off the ends of a string.

    Use a for loop to print the words.

提交回复
热议问题