Hoe je een string in Python kunt omkeren
- Previous Page Remove Duplicate Items from List
- Next Page Python Example
Leer hoe je een string in Python kunt omkeren.
Er is geen ingebouwde functie in Python om een string om te keren.
De snelste (en misschien ook de eenvoudigste?) manier is om een achterwaarts glijdende snede te gebruiken:-1
.
Instance
Omkeren van de string "Hello World":
txt = "Hello World"[::-1] print(txt)
Example Explanation
We hebben een string, "Hello World", en we willen deze omkeren:
te omkeren string
txt = "Hello World" [::-1] print(txt)
maakt een snede van een string die begint aan het einde en naar achteren beweegt.
In dit specifieke voorbeeld, de slice-syntaxis [::-1]
is equivalent to [11:0:-1]
, which means starting from position 11 (because "Hello "World" has 11 characters), ending at position 0, moving step length -1
, negative one means one step backward.
Cut String
txt = "Hello World" [::-1] print(txt)
Now we have a backward reading "Hello World" string txt
.
Print String to Demonstrate Result
Print List
txt = "Hello World"[::-1] print(txt)
Create Function
If you want a function that can send a string and return it backward, you can create a function and insert the code in the above example
Instance
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Example Explanation
Create a function with string as parameter.
Create Function
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Cut the string from the end and move backward.
Cut String
def my_function(x): return x [::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Return the reversed string.
Return String
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt )
Call Function Using String as Parameter:
Call Function
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Print Result:
Print Result
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
- Previous Page Remove Duplicate Items from List
- Next Page Python Example