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?
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With