2
votes

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?

5
Strings are immutable... So no. - Willem Van Onsem
Can I create another string, but bind it to the same variable at least? - klaus
Python has no call by ref. So again, no. - Willem Van Onsem
@ABDULNIYASPM , this would cause problems for cases like 'abca' , where according to your method, it would return bc - Kaushik NP
@ABDULNIYASPM : One thing you can do, though it will be unnecessarily complicated is by reversing the string , remove one element, and then reverse it back. Like so : s[::-1].replace(s[-1],'',1)[::-1] - Kaushik NP

5 Answers

6
votes

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.

4
votes

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'
1
votes

You could use bytearray instead:

s1 = bytearray(b'abcd')  # NB: must specify encoding if coming from plain string
s1.pop()     # now, s1 == bytearray(b'abc')
s1.decode()  # returns 'abc'

Caveats:

  • if you plan to filter arbitrary text (i.e. non pure ASCII), this is a very bad idea to use bytearray
  • in this age of concurrency and parallelism, it might be a bad idea to use mutation

By the way, perhaps it is an instance of the XY problem. Do you really need to mute strings in the first place?

0
votes

You can remove parts of a strings and assign it to another string:

s = 'abc'
s2 = s[1:]
print(s2)
0
votes

You wont do that.. you can still concatenate but you wont pop until its converted into a list..

>>> s = 'hello'
>>> s+='world'
>>> s
'helloworld'
>>> s.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'pop'
>>> list(s).pop()
'd'
>>> 

But still You can play with Slicing

>>> s[:-1]
'helloworl'
>>> s[1:]
'elloworld'
>>>