×

Python Slice from Last Occurrence of K

Introduction

We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on Python Strings, we may occasionally run across issues because we need to execute character removing on the last instance of an element. Data-related implementations for this are possible.

Before going to the topic lets understand some important definitions

Looping

The Python language has a process known as loops that enables the repeating of specific steps, scanning, or integration of a related set of steps repeatedly predicated just on keyword that enables such features being used, and that causes steps stipulated underneath the keyword to instantly indent appropriately.

String slicing

The slice operator is a new operator that Python offers. We could split the elements as needed with the use of a slice operator. Additionally, this operator works with all Python data types, including list, bucket, string, etc. The slice() method is also available in Python. With the aid of arguments, you can tell the slice operators and slice function what range to divide into.

rfind()

The highest index—or the substring's top right occurrence—in the text sequence is returned using the Python rfind() string function. By highest index, we mean that if a particular substring appears twice or three times in a string, the rfind() method would provide the top right or last instance of the substring, which is why we state that it provides the decisive factor of the substring.

There are many possible ways to implement this slicing from the last occurrence of K. few of the methods are

  1. Using of max() method
  2. Using string slicing along with rfind() method
  3. Using string slicing along with looping

max() Method Usage

In the below code, we will show how to use the max method.

Code

# example python program for implementation
# of Slice from Last Occurrence of K with
# the help of looping and string slicing


# declare any example string
string = ' Kill-the-goose-that-lays-the-golden-eggs '


# Declaring the K
K = "-"


x = []
result = []
for i in range( 0, len(string)):
    if(string[i] == K):
        x.append(i)
result = string[:max(x)]


# displaying the initialized string
print(' Declared String is = ' + str(string))


# displaying the string after slicing
print(' String after slicing is = ' + str(result))

Output

Declared String is =  Kill-the-goose-that-lays-the-golden-eggs 
String after slicing is =  Kill-the-goose-that-lays-the-golden-eggs 

String Slicing Combined with rfind()

Such issue can be fixed by combining the aforementioned techniques. In this, we retrieve the most recent occurrence utilizing rfind() and slice the remaining data using the previous way.

Code

# example python program for implementation
# of Slice from Last Occurrence of K with
# the help of string slicing and rfind()


# declare any example string
string = ' Kill-the-goose-that-lays-the-golden-eggs '


# Declaring the K
K = " - "


# Slicing from the Last Occurrence of the K with
# the help of rfind() and string slicing
index = string.rfind( K )
result = string[: index ]


# displaying the initialized string
print(' Declared String is = ' + str(string))


# displaying the string after slicing
print(' String after slicing is = ' + str(result))

Output

Declared String is =  Kill-the-goose-that-lays-the-golden-eggs 
String after slicing is =  Kill-the-goose-that-lays-the-golden-eggs 

Combining a Loop with String Cutting

This issue can be resolved by combining the aforementioned techniques. In this, we use a loop to look for the most recent occurrence and preserve the index for subsequent slicing.

Code

# example python program for implementation
# of Slice from Last Occurrence of K with
# the help of looping and string slicing


# declare any example string
string = ' Kill-the-goose-that-lays-the-golden-eggs '


# Declaring the K
K = " - "


# Slicing from the Last Occurrence of the K with
# the help of looping and string slicing
# set index to none
index = None
# initialize the loop
for i in range(len(string)):
	if K == string[ i ]:
		index = i
result = string[ : index ]
# displaying the initialized string
print(' Declared String is = ' + str(string))


# displaying the string after slicing
print(' String after slicing is = ' + str(result))

Output

Declared String is =  Kill-the-goose-that-lays-the-golden-eggs 
String after slicing is =  Kill-the-goose-that-lays-the-golden-eggs 

Related Topics

Python Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Isreal() 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...

4 minutes read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.