×

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 hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

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 Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 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 bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Add Element to Tuple in Python

Python: Popular high-level, all-purpose programming language Python. The new version of the Python programming language, Python 3, is used for all software applications, including web development. Python is the best programming...

4 minutes read.