Como reverter uma String em Python (5 Métodos)

Uma string é uma lista ordenada ou uma sequência de caracteres. Strings são uma das estruturas de dados que vem com Python. Como você está trabalhando com strings em Python, você pode querer ter todos os personagens invertidos. Um bom exemplo seria quando você está construindo um jogo palíndromo.

Uma string invertida tem seu primeiro caractere como o último caractere e assim por diante. No entanto, Python não vem com uma função interna para reverter strings, mas são métodos que você pode usar.

Neste tutorial, você aprenderá diferentes métodos para inverter a string em Python.

Método 1: Revinserir string em Python usando um loop For

O primeiro método para reverter strings é usar um loop for como no trecho de código abaixo:

Python Código:

# function for reversing a string
def reverse_string(string):
    # an empty string for storing reversed string
    reversed_string = ""
    # looping through the string
    for char in string:
        # reversing the string
        reversed_string = char + reversed_string
    # returning a reversed string
    return reversed_string

# the string to reverse
string = "Guru99"
# printing a message
print(f"String Reversal using a for loop")
# printing the original string
print(f"Original String: {string}")
# making a functional call inside a print function using an f-string
print(f"Reversed String: {reverse_string(string)}")

Saída:

String Reversal using a for loop
Original String: Guru99
Reversed String: 99uruG

Explicação do código:

  • Neste trecho de código, podemos usar string_reversa() função para reversão de string tomando um determinado corda como um argumento.
  • Dentro dele, podemos criar uma string vazia para armazenar a string invertida e, em seguida, faremos um loop pela string.
  • Os caracteres são invertidos e atribuídos ao string_revertida variável.
  • Finalmente, a última linha da função retorna a string invertida.
  • Para exibir a saída, estamos fazendo uma chamada funcional dentro do impressão() função com a ajuda de uma string f.

Método 2: Revinserir string em Python usando um loop While

Usando um enquanto entra em loop Python também seria outro método para reverter uma string. Vamos entender o trecho de código abaixo:

Python Código:

# declaring a string to reverse
string = "Python"
# initializing an empty string to store the reversed string
reversed_string = ""
# printing a message
print(f"String Reversal using a while loop")
# printing the original string
print(f"Original String: {string}")
# find length of a string and store in count variable
count = len(string)
# a while loop for looping through the string characters
while count > 0:
    # save the value of str[count-1] in reversed_string
    reversed_string += string[count - 1]
    # decrementing index
    count = count - 1
print(f"Reversed String: {reversed_string}")

Saída:

String Reversal using a while loop
Original String: Python
Reversed String: nohtyP

Explicação do código:

  • Neste curso Python código, estamos declarando uma string para ser invertida e, em seguida, uma string vazia para armazenar a string invertida.
  • Estamos então encontrando o comprimento da string que é atribuído ao contar variável.
  • A string[contagem – 1] em cada iteração recupera os caracteres da string do último para o primeiro.
  • E os concatena para string_revertida e então diminui o contar valor.
  • Finalmente, estamos imprimindo a string invertida.

Método 3: Python RevString diferente usando Slicer Operator

Outro método para reverter uma string é usar um operador de fatia. Para entender isso, veja o código abaixo:

Python Código:

# function to reverse a string
def reverse(string):
    # the  slice syntax
    reversed_string = string[::-1]
    return reversed_string

# declaring a string to reverse
string = "Let's guru99"
# printing a message
print(f"String Reversal using Slicer Operator")
# printing the original string
print(f"Original String: {string}")
# making a functional call inside a print function using an f-string
print(f"Reversed String: {reverse(string)}")

Saída:

String Reversal using Slicer Operator
Original String: Let's guru99
Reversed String: 99urug s'teL

Explicação do código:

  • Para criar um marcha ré() função que leva um corda como um argumento, dentro dele
  • Neste exemplo, temos um string[::-1] operador de fatia para reverter o corda
  • Então a string invertida é atribuída a uma nova variável chamada string_revertida
  • Finalmente, a nova string invertida é retornada

Método 4: Revinserindo uma String em Python usando a função reversed()

Também podemos reverter uma string usando um invertido () Python função, o código ficaria assim:

Python Exemplo de código:

# function to reverse a string
def reverse(string):
    # reversed() function inside the join() function
    string = "".join(reversed(string))
    # returning the reversed string
    return string

# declaring a string to reverse
string = "guru99"
# printing a message
print(f"String Reversal using reversed() function")
# printing the original string
print(f"Original String: {string}")
# making a functional call inside a print function using an f-string
print(f"Reversed String: {reverse(string)}")

Saída:

String Reversal using reversed() function
Original String: guru99
Reversed String: 99urug

Explicação do código:

  • Neste código, temos um invertido () função cujo argumento é um corda.
  • Dentro dele, inicializamos uma string vazia.
  • Nós o concatenamos com a saída de invertido (string) usando o Junte-se() função.
  • Fora da invertido () função, declaramos uma string para reverter, então estamos imprimindo a string original e a string invertida.

Método 5: Python RevErse String usando recursão

Recursão significa uma função definida chamando a si mesma. Dizemos que uma função recursiva é recursiva quando chama a si mesma. Para entender melhor veja o seguinte exemplo de código:

Python Código:

# a function to reverse a string
def reverse(string):
    # Checking the length of string
    if len(string) == 0:
        return string
    # reversing string if len(string) != 0
    else:
        # recursively calling the reverse() function
        return reverse(string[1:]) + string[0]

# declaring a string to reverse
string = "I love guru99"
# printing a message
print(f"String Reversal using Recursion")
# printing the original string
print(f"Original String: {string}")
# making a functional call inside a print function using an f-string
print(f"Reversed String: {reverse(string)}")

Saída:

String Reversal using Recursion
Original String: I love guru99
Reversed String: 99urug evol I

Explicação do código:

  • No código acima, declaramos um reverter () função que leva um corda como argumento, o corpo da função é um se mais declaração.
  • A if instrução verifica se o comprimento da string é equivalente a 0 e retorna a string, enquanto o outro declaração chama o marcha ré() função recursivamente, corta o último índice da string e o adiciona ao início.

Conclusão

  • Este Python tutorial o guiou pela reversão de strings usando vários métodos em Python.
  • Podemos usar a função reverse_string() para reversão de string tomando uma determinada string como argumento.
  • Você também pode usar “for e while loop” para agitação reversa.
  • Você pode processar uma função invertida que usa uma string como argumento.
  • Ao escolher esses métodos, você deve considerar seu desempenho como um dos fatores.