In this Python tutorial, we will discuss on Slicing string in Python with a few examples.
- Slicing string in Python
- reverse string slicing in python
- reverse string python using slicing
Slicing string in Python
Python slicing is about obtaining a sub-string from the given string by slicing it. For getting the part of the string we will specify the start index and the end index, separated by the colon.
my_str = "Welcome, to Python!" print(my_str[3:7])
After writing the above code (slicing a string python), you will print “my_str[3:7]” then the output will appear as “ come ”. Here, you will get the characters from position 3 to position 7 not included.
You can refer to the below screenshot slicing a string python.
Reverse slicing of a string in Python
Now, let us see the code for reverse slicing of a string in Python.
For reverse slicing of a given string we will use join() and reversed(). We reverse the string in memory and join the sliced number of characters and it will return a string.
my_str = "PythonGuides" print("Original string is: " + my_str) v = 6 result = ' '.join(reversed(my_str[0:v])) print("The reversed sliced string is: " +result)
After writing the above code (reverse slicing of a given string in python), once you will print the “result” then the output will appear as “The reversed sliced string is: nohtyP”. Here, it will return the sliced reversed string.
You can refer to the below screenshot reverse slicing of a given string in python.
This is an example of reverse string slicing in python.
Reverse string python using slicing
In python, to reverse a string in python there is no built-in function so, we will use slice that starts from the end of the string with a negative value and ends at 0.
my_string = "PythonGuide"[::-1] print(my_string)
After writing the above code (how to reverse a string in python), Ones you will print then the output will appear as an “ ediuGnohtyP ”. Here, we will use the string slicing to reverse the string.
You can refer to the below screenshot python reverse a string in python
This is how to reverse a string in python using slicing.
You may like the following Python tutorial:
- How to split a string using regex in python
- Remove character from string Python
- How to handle indexerror: string index out of range in Python
- How to convert list to string in Python
- How to convert an integer to string in python
- How to create a string in Python
- Python compare strings
- Python NumPy nan
In this tutorial, we learned slicing string in python and reverse string slicing in python.
- Reverse string python using slicing