×

How to reverse a string in python

How to reverse a string in python

A Brief About Strings-

  1. The String is a data type in Python that has a sequence of characters. This series of characters are represented in single, double or triple quotes. Python has a built-in string class called ‘str’.

For example-

 Name=’Darcy’
 Nationality=” British”
 Message= “Hello World” 
  • The characters of strings can be accessed using the indexes. The expression [ ] in brackets is called an index.

For example-

message = “TENET”

The characters of this string can be accessed as-

 message [0] = T
 message [1] = E
 message [2] = N
 message [3] = E
 message [4] = T 
  • They are immutable which means they cannot be changed. A new string is created when we try to change or modify the existing string variable. Using id(), we can get the memory addresses of objects.
  • The feature of slicing present in strings can help us to fetch the characters of our choice. The syntax of slice operation is s[start:end].

Start specifies the beginning index of the substring.

End specifies the last character index of the substring.

a='CORSICA'                                                       OUTPUT

print(a[1:5])                                                              ORSI

print(a[1:])                                                              ORSICA

print(a[:6])                                                              CORSIC

  • Regular Expressions are an influential tool for different kinds of manipulation of our strings. They can be accessed using the re module.

Regular expressions help us to match or find strings in another strings.

Some of its examples are-

  1. match() function- This function matches the pattern with a string. It gives the desired output only when the match is found at the beginning of string.

Syntax –

re.match(pattern,string,flags=0)
  • search() function- This function matches the pattern with a string. The match of a pattern can occur anywhere in the string.

Syntax –

re.search(pattern,string,flags=0)
  • sub() function- It is used to search a pattern and then it is replaced by another pattern.

Syntax –

re.sub(pattern,repl,string)
  • findall() function- It searches a string and then returns a list of matches of the pattern in the string.

Syntax –

 re.findall(pattern,input_str,flags=0)

Let’s understand our objective here,

If we have a string named ‘CORSICA’, we are supposed to obtain the reverse of this string in our output.

Input String – ‘CORSICA’

Output String – ‘ACISROC’

The different approaches that we can use to implement this are-

1. Using the for loop and concatenating the letters in reverse format and storing them in a variable.

2. Using the reverse() function.

3. Using the slicing operation

METHOD I

In python, for-loop helps us to pick each element from the string and perform the expected functionality on it according to the conditions.

So, let's have a glance on what's the step-by-step approach we'll use here-

  1. Take your input string.
  2. Now with the help of for loop, it will take each character from the string and append it in the variable and it will be appended in the reverse format.
  3. Now we will print the variable in which we have stored this value.
 def reverse(string): 
     revstr=''   
     for i in string: 
         revstr = i + revstr 
     return revstr 
 string = "CORSICA"          
 print("Original string: ",string) 
 print("Reverse string: ",reverse(string)) 
How to reverse a string in python

METHOD II

Functions in Python helps in the redundancy of our code and make it easy to comprehend.

Python is popular and well-accepted because of its versatile nature. The reverse() function helps us to obtain the reverse of the string.

Following are the steps-

  1. We will use the reverse() function inside the join function since join takes each iterable and converts it into a string.
  2. Then we call the function to display the desired result.
 def reverse(str):
     string=' ‘. join(reversed(str))
     return string
 my_string='CORSICA'
 print("Original string: ",my_string)
 print("Reversed string: ",reverse(my_string)) 
How to reverse a string in python

METHOD III

Slicing is a great technique when we want to play with the letters of our string. So here we have three parameters i.e., start, stop and step.

Let’s understand the procedure here-

The reverse of string can be obtained by initializing

Start as -1(since we have to start with the last character of the string)

Step as -1(Traversing in the backward direction)

And leaving the end as blank.

Again, we can call our function to display the required results.

 def reverse(string):
     string=string[-1::-1]
     return string
 my_string='CORSICA'
 print("Original string: ",my_string)
 print("Reversed string: ",reverse(my_string)) 
How to reverse a string in python

Related Topics

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Enumerate() Function in Python

The enumerate() function in Python is used to convert a data collection object into an enumerate object. It returns an object that contains a counter as a key for each...

3 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

YOLO Python

YOLO means you only look once.It is a technique to perform object detection is called YOLO. It is the algorithmused by the program to identify items in the image. Earlier detection...

4 minutes read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.