Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function to modify string

I was asked once to create a function that given a string, remove a few characters from the string.

Is it possible to do this in Python?

This can be done for lists, for example:

def poplist(l):
    l.pop()

l1 = ['a', 'b', 'c', 'd']

poplist(l1)
print l1
>>> ['a', 'b', 'c']

What I want is to do this function for strings. The only way I can think of doing this is to convert the string to a list, remove the characters and then join it back to a string. But then I would have to return the result. For example:

def popstring(s):
    copys = list(s)
    copys.pop()
    s = ''.join(copys)

s1 = 'abcd'

popstring(s1)

print s1
>>> 'abcd'

I understand why this function doesn't work. The question is more if it is possible to do this in Python or not? If it is, can I do it without copying the string?

like image 664
klaus Avatar asked Sep 01 '25 16:09

klaus


2 Answers

Strings are immutable, that means you can not alter the str object. You can of course construct a new string that is some modification of the old string. But you can thus not alter the s object in your code.

A workaround could be to use a container:

class Container:

    def __init__(self,data):
        self.data = data

And then the popstring thus is given a contain, it inspect the container, and puts something else into it:

def popstring(container):
    container.data = container.data[:-1]

s1 = Container('abcd')
popstring(s1)

But again: you did not change the string object itself, you only have put a new string into the container.

You can not perform call by reference in Python, so you can not call a function:

foo(x)

and then alter the variable x: the reference of x is copied, so you can not alter the variable x itself.

like image 168
Willem Van Onsem Avatar answered Sep 04 '25 04:09

Willem Van Onsem


Strings are immutable, so your only main option is to create a new string by slicing and assign it back.

#removing the last char

>>> s = 'abcd'
>>> s = s[:-1]
=> 'abc'

Another easy to go method maybe to use list and then join the elements in it to create your string. Ofcourse, it all depends on your preference.

>>> l = ['a', 'b', 'c', 'd']
>>> ''.join(l)
=> 'abcd'

>>> l.pop()
=> 'd'

>>> ''.join(l)
=> 'abc'

Incase you are looking to remove char at a certain index given by pos (index 0 here), you can slice the string as :

>>> s='abcd'

>>> s = s[:pos] + s[pos+1:]
=> 'abd'
like image 26
Kaushik NP Avatar answered Sep 04 '25 04:09

Kaushik NP