klaus
klaus

Reputation: 1237

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?

Upvotes: 4

Views: 17619

Answers (5)

YvesgereY
YvesgereY

Reputation: 3888

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?

Upvotes: 1

Kaushik NP
Kaushik NP

Reputation: 6789

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'

Upvotes: 4

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20206

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

Upvotes: 0

mrCarnivore
mrCarnivore

Reputation: 5088

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

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

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

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.

Upvotes: 6

Related Questions