Reverse a string in Python

前端 未结 28 3595
南旧
南旧 2020-11-21 04:41

There is no built in reverse function for Python\'s str object. What is the best way of implementing this method?

If supplying a very conci

28条回答
  •  生来不讨喜
    2020-11-21 05:12

    The existing answers are only correct if Unicode Modifiers / grapheme clusters are ignored. I'll deal with that later, but first have a look at the speed of some reversal algorithms:

    list_comprehension  : min:   0.6μs, mean:   0.6μs, max:    2.2μs
    reverse_func        : min:   1.9μs, mean:   2.0μs, max:    7.9μs
    reverse_reduce      : min:   5.7μs, mean:   5.9μs, max:   10.2μs
    reverse_loop        : min:   3.0μs, mean:   3.1μs, max:    6.8μs
    

    list_comprehension  : min:   4.2μs, mean:   4.5μs, max:   31.7μs
    reverse_func        : min:  75.4μs, mean:  76.6μs, max:  109.5μs
    reverse_reduce      : min: 749.2μs, mean: 882.4μs, max: 2310.4μs
    reverse_loop        : min: 469.7μs, mean: 577.2μs, max: 1227.6μs
    

    You can see that the time for the list comprehension (reversed = string[::-1]) is in all cases by far the lowest (even after fixing my typo).

    String Reversal

    If you really want to reverse a string in the common sense, it is WAY more complicated. For example, take the following string (brown finger pointing left, yellow finger pointing up). Those are two graphemes, but 3 unicode code points. The additional one is a skin modifier.

    example = "

提交回复
热议问题