Efficient way to add spaces between characters in a string

前端 未结 3 746
南笙
南笙 2020-12-03 09:56

Say I have a string s = \'BINGO\'; I want to iterate over the string to produce \'B I N G O\'.

This is what I did:

result =         


        
相关标签:
3条回答
  • 2020-12-03 10:41

    A very pythonic and practical way to do it is by using the string join() method:

    str.join(iterable)
    

    The official Python documentations says:

    Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.

    How to use it?

    Remember: this is a string method.

    This method will be applied to the str above, which reflects the string that will be used as separator of the items in the iterable.

    Let's have some practical example!

    iterable = "BINGO"
    separator = " " # A whitespace character.
                    # The string to which the method will be applied
    separator.join(iterable)
    > 'B I N G O'
    

    In practice you would do it like this:

    iterable = "BINGO"    
    " ".join(iterable)
    > 'B I N G O'
    

    But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.

    iterable = ['B', 'I', 'N', 'G', 'O']    
    " ".join(iterable)
    > 'B I N G O'
    

    What happens if you use a hyphen as a string instead?

    iterable = ['B', 'I', 'N', 'G', 'O']    
    "-".join(iterable)
    > 'B-I-N-G-O'
    
    0 讨论(0)
  • 2020-12-03 10:49
    s = "BINGO"
    print(" ".join(s))
    

    Should do it.

    0 讨论(0)
  • 2020-12-03 10:57
    s = "BINGO"
    print(s.replace("", " ")[1: -1])
    

    Timings below

    $ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
    1000000 loops, best of 3: 0.584 usec per loop
    $ python -m timeit -s's = "BINGO"' '" ".join(s)'
    100000 loops, best of 3: 1.54 usec per loop
    
    0 讨论(0)
提交回复
热议问题