python find substrings based on a delimiter

后端 未结 4 1868
离开以前
离开以前 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:13

    Simple thanks to the convenient string methods in Python:

    print "\n".join(token.strip() for token in string.split(","))
    

    Output:

    The
    world
    is
    a
    happy
    place
    

    By the way, the word string is a bad choice for variable name (there is an string module in Python).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • Another option:

    import re
    
    string = "The , world , is , a , happy , place "
    match  = re.findall(r'[^\s,]+', string)
    for m in match:
        print m
    

    Output

    The
    world
    is
    a
    happy
    place
    

    See a demo

    You could also just use match = re.findall(r'\w+', string) and you will get the same output.

    0 讨论(0)
  • 2021-01-17 18:26

    Try using the split function.

    In your example:

    string = "The , world , is , a , happy , place "
    array = string.split(",")
    for word in array:
        print word
    

    Your approach failed because you indexed it to yield the string from beginning until the first ",". This could work if you then index it from that first "," to the next "," and iterate across the string that way. Split would work out much better though.

    0 讨论(0)
提交回复
热议问题