Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Examples Python Basics Python Indentation Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Python Recursion Anonymous/Lambda Function in Python python apply() Function Python lambda() Function

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Python Super function Python Static Method Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Math Module Python Import Module Python Time Module Python Random Module Python Calendar Module CSV Module in Python Python Subprocess Module Python Subprocess

Python MySQL

Python MySQL Python MySQL Client Update Operation Delete Operation Database Connection Creating new Database using Python MySQL Creating Tables Performing Transactions

Python MongoDB

Python MongoDB

Python SQLite

Python SQLite

Python Data Structure Implementation

Python Stack Python Queue Python Linked List Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Linear regression Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Python Collections Python Commands Python Data Visualization Python Debugger Python DefaultDict Python Enumerate

Python 3

Anaconda in Python 3 Anaconda python 3 installation for windows 10 List Comprehension in Python3

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Best resources to learn Numpy and Pandas in python Check Letter in a String Python Python Console Python Control Statements Convert Float to Int in Python using Pandas Difference between python list and tuple Importing Numpy in Pycharm Python Key Error Python NewLine Python tokens and character set Python Strong Number any() Keyword in python Best Database in Python Check whether dir is empty or not in python Comments in the Python Programming Language Convert int to Float in Python using Pandas Decision Tree Classification in Python End Parameter in python __GETITEM__ and __SETITEM__ in Python Python Namespace Python GUI Programming List Assignment Index out of Range in Python List Iteration in Python List Index out of Range Python for Loop List Subtract in Python Python Empty Tuple Python Escape Characters Sentence to python vector Slicing of a String in Python Executing Shell Commands in Python Genetic Algorithm in python Get index of element in array in python Looping through Data Frame in Python Syntax of Map function in Python After Python What Should I Learn Python AIOHTTP Alexa Python Artificial intelligence mini projects ideas in python Artificial intelligence mini projects with source code in Python Find whether the given stringnumber is palindrome or not First Unique Character in a String Python Python Network Programming Python Interface Python Multithreading Python Interpreter Data Distribution in python Flutter with tensor flow in python Front end in python Iterate a Dictionary in Python Iterate a Dictionary in Python – Part 2 Allocate a minimum number of pages in python Assertion Errors and Attribute Errors in Python Checking whether a String Contains a Set of Characters in python Python Control Flow Statements *Args and **Kwargs in Python Bar Plot in Python Conditional Expressions in Python Function annotations() in Python How to Write a Configuration file in Python Image to Text in python import() Function in Python Import py file in Python Multiple Linear Regression using Python Nested Tuple in Python Python String Negative Indexing Reading a File Line by Line in Python Python Comment Block Base Case in Recursive function python ER diagram of the Bank Management System in python Image to NumPy Arrays in Python NOT IN operator in Python One Liner If-Else Statements in Python Sklearn in Python Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Bitwise Operators Python Identifiers Python Matrix Multiplication Python AND Operator Python Logical Operators Python Multiprocessing Python Unit Testing __init__ in Python Advantages of Python Is Python Case-sensitive when Dealing with Identifiers Python Boolean Python Call Function Python History Python Image Processing Python main() function Python Permutations and Combinations Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python

How to

How to Substring a String in Python How to Iterate through a Dictionary in Python How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python How to Open a file in python with Path How to run a Python file in CMD How to change the names of Columns in Python How to Concat two Dataframes in Python How to Iterate a List in Python How to learn python Online How to Make an App with Python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is.

String

String is a group of characters that are stored under a certain variable. Python does not have a character data type. So a string with single variable is called as a character in Python. String is a data type which represented as str in Python. These strings are stored as character arrays in a variable.

We can access these strings using indexing. Highly, indexing is used because it is an easy way of accessing characters in a string.

String index positions are represented as following.

Example:

Let us a string for an example for explaining indexing in a string
S=”JOE ROOT
INDEX:	            0 1 2 3 4 5 6 7	
CHARACTER:  J O E     R O O T
LENGTH OF THE STRING IS: 8
The given string contains 7 characters and a space.

We can finally say that the way of indexing strings and the way of indexing arrays are same.

Properties:

1.) String is immutable.

The way in which the contents of the given data type can be changed is called mutability.

The strings are immutable. Immutable means the characters inside a character array cannot be changed. Let us understand this with the help of an example.

Example:

File Name: James.py

'''
This is an example program to know whether a string is mutable or immutable or not.


If string changes then it is called as mutable


If the string does not change then it is called as immutable


'''
String="JAMES ANDERSON"


print (String [6])


# let us try to change this output A with other character 'X'


# If this change is possible then the output is termed as JAMES XANDERSON


String [6] ='X'

OUTPUT

A
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    String[6]='X'
TypeError: 'str' object does not support item assignment

So, we can prove that string is mutable and if we break the property of mutability, then we face and error of TypeError. So, String is mutable.

2. %s is the format specifier of string in Python.

Let us explain %s with the help of an example program.

Example:

String="JAMES ANDERSON"




print ("Greatest fast bowler of cricket is %s"%String)

Output:

Greatest fast bowler of cricket is JAMES ANDERSON

There is always some specialty if a data type is used very highly. Similarly, there is a specialty for Strings for it is wide usage. The specialty is slicing of the string

Slicing:

The sub-string of a string is called as slice. The process of creating slices using an operator is called slicing operator. The slice operator is used to refer sub parts of sequences. We can take a subset of original string by using [] (square brackets). The square brackets are known as delimiters of slicing operation.

We use indices (plural form of index) for slicing.

Syntax:

String_name [start : stop :step count]

Let us understand slicing with the help of an example.

Example:

'''
This is a program written to know how a slicing operator is working in Python on a string
'''


string="RAHUL DRAVID"


# to know whether the variable s is a string or not.
print(type(string))


# indexing operation in Python


print("THE string in position 5 is '"+string[5]+"'")




# length of the string
print("The length of the string is", len (string))


# slicing operation


# syntax string_name[start_index : end_index]


print("The sub string from 1st position to 7th position is:")


print(string[1:7])


# now the characters from index 1 to index 6 are printed


# syntax string_name[start_index : end_index: step count]




print("The sub string from 1st position to 7th position with step count 2 is:")


print(string[1:7:2])


# example 2


print("to print the whole string using indexing is :")


print(string[0 : len(string)])

Output:

<class 'str'>


THE string in position 5 is ' '


The length of the string is 12


The string from 1st position to 7th position is:


AHUL D


The string from 1st position to 7th position with step count 2 is:
AU
RAHUL DRAVID

Explanation:

CharacterRAHUL DRAVID
Index01234567891011

So as shown in the above table. This is how an index value is assigned to the given string.

So the first code written is:

syntax string_name[start_index : end_index]

string= “RAHUL DRAVID”

print (string[1:7])

The output is 

AHUL D

The output is in that way because according to the concept of indexing the characters are printed in such a way that the printing starts from index 1 (which is the start index) to the index 7-1 =6 (which is the end index) . Here according to the rules of slicing the index of end value minus one is printed

So that is the reason why

AHUL  D is printed

CharacterAHUL D
Index123456

syntax string_name[start_index : end_index: step count]

string= “RAHUL DRAVID”

print (string[1 : 7 : 2])

The output of the above code is:

AU

The output can be separately differentiated as ‘A’ ,‘U’, ‘  ‘

Here 3 characters A, U, A space is printed

Here the characters are printed in the way that :

Start index which is to be printed is: 1

End index which is to be printed is : 7-1=6

Step count of the slice is: 2

So according to step count and rules of slicing the indices of:

1, 1+= 3, 3+2 =5, 5+2=7 (out of slicing end value range)

So 1st , 3rd , 5th indices are printed

CharactersAU“  “( the value in quotations is empty space
Index11+2=  33+2=  5

So due to this reason the output is AU

If we get a question based on indices, follow these steps:

  1. Print start index character
  2. Then add step count to start index
  3. Continue this process
  4. Stop this process when the value of index crosses the end-1 value.

There is a one more advantage in slicing. Here we can use negative indices for getting a slice or the substring of the given String.

Negative Index Slicing Representation:

To explain the negative indices in Python which is working on Python strings let us see how the below program works.

Example:

'''
This is a program written to know how a slicing operator with the help of negative indexing is working in Python on a string
'''


string="RAHUL DRAVID"


# length of the string


print("The length of the string is")


print(len(string))
# slicing of the given string using negative indices


# syntax = string_name [ start : end ]


print("The sub string from position -6 to ( -1-1)= -2 position ")


print(string[-6 : -1])






# syntax = string_name [ start : end : step count]




print("The sub string from position -6 to ( -1-1)= -2 position with step count equals to two (step count = 2) ")


print(string[-6 : -1 : 2])




# example 2


print("The given string in reverse format")


print(string[ : : -1])

Output:

The length of the string is


12


D


The sub string from position -6 to ( -1-1)= -2 position 


DRAVI


The sub string from position -6 to ( -1-1)= -2 position with step count equals to two (step count 
= 2) is 


DAI


The given string in reverse format


DIVARD LUHAR

Explanation:

CharacterRAHUL DRAVID
Positive Index01234567891011
Negative Index-12-11-10-9-8-7-6-5-4-3-2-1

Negative slicing in Python.

This method is also similar to positive slicing.

print(string[-6])

The output is D

The reason is because the character D is present at the position (or) index -6.

print(string[-6 : -1])

The output is

DRAVI

CharacterDRAVI
Index-6-5-4-3-2

The output is in that way because according to the concept of indexing the characters are printed in such a way that the printing starts from index -6 (which is the start index) to the index -1-1 =-2 (which is the end index) . Here according to the rules of slicing the index of end value minus one is printed

So the output is DRAVI

print(string[-6 : -1 : 2])

The output is

DAI

Here the characters are printed in the way that :

Start index which is to be printed is: -6

End index which is to be printed is : -1-1=-2

Step count of the slice is: 2

So according to step count and rules of slicing the indices of:

-6, -6+2= -4, -4+2 =-2, -2+2=0 (out of slicing end value range)

So -6th, -4th, -2nd  indices are printed

CharactersDAI
Index-6-6+2=-4-4+2=-2

print( string[::-1])

Here the string is printed in reverse manner.

Start is taken as – (length of string)

End is taken as –1

This process is done internally directly by the compiler.

So the output is

DIVARD LUHAR

This is how slicing is done on a string.



ADVERTISEMENT
ADVERTISEMENT