Making two string methods into one method

75 views Asked by At

I want to put two string methods together so that they can be used as a shorter method. Specifically I am trying to make a method that will both make a string lowercase and remove punctuation. Regularly you can just do:

import string
s.translate(str.maketrans('', '', string.punctuation)).lower()

but I want it to look like:

s.removeall()

I've tried defining a function but I'm not sure how I would go about actually putting it into one sense it doesn't connect to anything and python wouldn't read it as a method anyways.

I tried this:

import string
def removeall():
    translate(str.maketrans('', '', string.punctuation)).lower()

s.removeall()
1

There are 1 answers

0
Mad Physicist On BEST ANSWER

You wouldn't be able to make a method of str easily, but there's nothing stopping you from writing a standalone utility function:

def removeall(s):
    return s.translate(str.maketrans('', '', string.punctuation)).lower()

You would use it as s = removeall(s). Keep in mind that strings are immutable objects. There is no such thing as an in-place operation on a string. Your original expression s.translate(str.maketrans('', '', string.punctuation)).lower() creates a new string, and therefore has no net effect if you don't save the result. The same applies for the function from.