Fabrication industrielle
Internet des objets industriel | Matériaux industriels | Entretien et réparation d'équipement | Programmation industrielle |
home  MfgRobots >> Fabrication industrielle >  >> Industrial programming >> Python

5 techniques expertes pour inverser les chaînes en Python

Une chaîne est une liste ordonnée ou une séquence de caractères. Les chaînes sont l'une des structures de données fournies avec Python. Lorsque vous travaillez avec des chaînes en Python, vous souhaiterez peut-être inverser tous les caractères. Un bon exemple serait lorsque vous créez un jeu palindrome.

Une chaîne inversée a son premier caractère comme dernier caractère et ainsi de suite. Cependant, Python n'est pas livré avec une fonction intégrée pour inverser les chaînes, mais ce sont des méthodes que vous pouvez utiliser.

Dans ce didacticiel, vous apprendrez différentes méthodes pour inverser la chaîne en Python.

Méthode 1 :Inverser une chaîne en Python à l'aide d'une boucle For

La première méthode pour inverser des chaînes consiste à utiliser une boucle for comme dans l'extrait de code ci-dessous :

Code Python :

# 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)}")

Résultat :

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

Explication du code :

Méthode 2 :Inverser une chaîne en Python à l'aide d'une boucle While

Utiliser une boucle while en Python serait également une autre méthode pour inverser une chaîne. Comprenons l'extrait de code ci-dessous :

Code Python :

# 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}")

Résultat :

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

Explication du code :

Méthode 3 :Chaîne inversée Python à l'aide de l'opérateur Slicer

Une autre méthode pour inverser une chaîne consiste à utiliser un opérateur slice. Pour vous y retrouver, consultez le code ci-dessous :

Code Python :

# 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)}")

Résultat :

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

Explication du code :

Méthode 4 : Inverser une chaîne en Python à l'aide de la fonction reverse()

Nous pouvons également inverser une chaîne en utilisant un reversed() Fonction Python, le code ressemblerait à ceci :

Exemple de code Python :

# 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)}")

Résultat :

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

Explication du code :

Méthode 5 :Chaîne inversée Python utilisant la récursion

La récursivité signifie une fonction définie qui s'appelle elle-même. Une fonction récursive est dite récursive lorsqu’elle s’appelle elle-même. Pour mieux le comprendre, regardez l'exemple de code suivant :

Code Python :

# 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)}")

Résultat :

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

Explication du code :

Conclusion

Résumez ce message avec :


Python

  1. Python Vs Ruby :Différence entre Ruby et Python
  2. Python - Prise de décision
  3. Python Renommer le fichier et le répertoire à l'aide de os.rename()
  4. Python JSON :encoder (dumps), décoder (chargers) et lire le fichier JSON
  5. Explorez la collection de livres officiels de Real Python – Maîtrisez Python du débutant au avancé
  6. Heures de bureau réelles de Python :sessions de questions-réponses en direct pour les apprenants de Python
  7. Flask vs Django :Quelle est la différence entre Flask et Django ?
  8. Python - Programmation multithread
  9. Répertoire Python et gestion des fichiers