×

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

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

AX Contour in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph....

3 minutes read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

How to Substring a String in Python

String Unicode characters collection is referred to as a String. It consists of a succession of characters, including alphanumeric and special characters. Substring: Core Concept A substring is a piece of a string....

5 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.