天天看點

python字元串反向輸出_Python反向字元串– 5種方法和最佳方法

python字元串反向輸出

Python String doesn’t have a built-in reverse() function. However, there are various ways to reverse a string in Python.

Python String沒有内置的reverse()函數。 但是,有多種方法可以在Python中反轉字元串。

1.如何在Python中反轉字元串? (1. How to Reverse a String in Python?)

Some of the common ways to reverse a string are:

反轉字元串的一些常見方法是:

  • Using Slicing to create a reverse copy of the string.

    使用切片來建立字元串的反向副本。

  • Using for loop and appending characters in reverse order

    使用for循環并以相反順序附加字元

  • Using while loop to iterate string characters in reverse order and append them

    使用while循環以相反的順序疊代字元串字元并追加它們

  • Using string join() function with reversed() iterator

    在反向()疊代器中使用字元串join()函數

  • Creating a list from the string and then calling its

    reverse()

    function

    從字元串建立清單 ,然後調用其

    reverse()

    函數
  • Using Recursion

    使用遞歸

1.1)使用切片的Python反向字元串 (1.1) Python Reverse String using Slicing)

def reverse_slicing(s):
    return s[::-1]

input_str = 'ABç∂EF'

if __name__ == "__main__":
    print('Reverse String using slicing =', reverse_slicing(input_str))
           

If you run above Python script, the output will be:

如果您在Python腳本上運作,則輸出将是:

Reverse String using slicing = FE∂çBA
           

1.2)使用For循環反向字元串 (1.2) Reverse String using For Loop)

def reverse_for_loop(s):
    s1 = ''
    for c in s:
        s1 = c + s1  # appending chars in reverse order
    return s1

input_str = 'ABç∂EF'

if __name__ == "__main__":
    print('Reverse String using for loop =', reverse_for_loop(input_str))
           

Output:

Reverse String using for loop = FE∂çBA

輸出:

Reverse String using for loop = FE∂çBA

1.3)使用While循環反轉字元串 (1.3) Reverse a String using While Loop)

def reverse_while_loop(s):
    s1 = ''
    length = len(s) - 1
    while length >= 0:
        s1 = s1 + s[length]
        length = length - 1
    return s1

input_str = 'ABç∂EF'

if __name__ == "__main__":
    print('Reverse String using while loop =', reverse_while_loop(input_str))
           

1.4)使用join()和reversed()反轉字元串 (1.4) Reverse a String using join() and reversed())

def reverse_join_reversed_iter(s):
    s1 = ''.join(reversed(s))
    return s1
           

1.5)使用清單reverse()的Python反向字元串 (1.5) Python Reverse String using List reverse())

def reverse_list(s):
    temp_list = list(s)
    temp_list.reverse()
    return ''.join(temp_list)
           

1.6)使用遞歸的Python反向字元串 (1.6) Python Reverse String using Recursion)

def reverse_recursion(s):
    if len(s) == 0:
        return s
    else:
        return reverse_recursion(s[1:]) + s[0]
           

2.用Python反轉字元串的最佳方法 (2. Best Way to Reverse a String in Python)

We can reverse a string through multiple algorithms. We have already seen six of them. But which of them you should choose to reverse a string.

我們可以通過多種算法反轉字元串。 我們已經看過其中的六個。 但是您應該選擇其中的哪一個反向字元串。

We can use timeit module to run multiple iterations of these functions and get the average time required to run them.

我們可以使用timeit子產品來運作這些函數的多次疊代,并獲得運作它們所需的平均時間。

All the above functions are stored in a python script named

string_reverse.py

. I executed all these functions one by one for 1,00,000 times using the timeit module and got the average of the best 5 runs.

以上所有功能均存儲在名為

string_reverse.py

的python腳本中。 我使用timeit子產品一個接一個地執行了所有這些功能1,00,000次,并得到了最佳5次運作的平均值。

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_slicing("ABç∂EF"*10)'
100000 loops, best of 5: 0.449 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_list("ABç∂EF"*10)'
100000 loops, best of 5: 2.46 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_join_reversed_iter("ABç∂EF"*10)'
100000 loops, best of 5: 2.49 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_for_loop("ABç∂EF"*10)'
100000 loops, best of 5: 5.5 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_while_loop("ABç∂EF"*10)'
100000 loops, best of 5: 9.4 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_recursion("ABç∂EF"*10)'
100000 loops, best of 5: 24.3 usec per loop
           

The below table presents the results and slowness of an algorithm from the best one.

下表列出了最佳算法的結果和慢度。

Algorithm TimeIt Execution Time (Best of 5) Slowness
Slicing 0.449 usec 1x
List reverse() 2.46 usec 5.48x
reversed() + join() 2.49 usec 5.55x
for loop 5.5 usec 12.25x
while loop 9.4 usec 20.94x
Recursion 24.3 usec 54.12x
算法 TimeIt執行時間(最佳5) 緩慢
切片 0.449微秒 1倍
列出reverse() 2.46微秒 5.48倍
reversed()+ join() 2.49微秒 5.55倍
for循環 5.5微秒 12.25倍
while循環 9.4用 20.94倍
遞歸 24.3微秒 54.12倍

3.總結 (3. Summary)

We should use slicing to reverse a string in Python. Its code is very simple and small and we don’t need to write our own logic to reverse the string. Also, it’s the fastest way to reverse a string as identified by the above test executions.

我們應該使用切片來反轉Python中的字元串。 它的代碼非常簡單小巧,我們不需要編寫自己的邏輯來反轉字元串。 另外,這是反轉上述測試執行所确定的字元串的最快方法。

GitHub Repository. GitHub存儲庫中檢出完整的python腳本和更多Python示例。

4.參考 (4. References)

  • reversed() API Doc

    reversed()API文檔

  • str.join() API Doc

    str.join()API文檔

翻譯自: https://www.journaldev.com/23647/python-reverse-string

python字元串反向輸出