4

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?

7
  • 2
    Strings are immutable... So no. Commented Oct 20, 2017 at 14:05
  • Can I create another string, but bind it to the same variable at least? Commented Oct 20, 2017 at 14:07
  • Python has no call by ref. So again, no. Commented Oct 20, 2017 at 14:09
  • @ABDULNIYASPM , this would cause problems for cases like 'abca' , where according to your method, it would return bc Commented Oct 20, 2017 at 14:17
  • 1
    @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] Commented Oct 20, 2017 at 14:30

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is sort of what I was expecting as a solution.
4

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 Comment

the problem with this is that if you are inside a function you have to return the string, so you have it both as an input parameter and as an output parameter; not exactly elegant; alternatively you could build up a list and convert it to a string at a later point
1

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?

1 Comment

This is better than using a list I think. Is it possible to convert it back to a string?
0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.