Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Remove last char from string and return it

Tags:

python

While I know that there is the possibility:

>>> a = "abc"
>>> result = a[-1]
>>> a = a[:-1]

Now I also know that strings are immutable and therefore something like this:

>>> a.pop()
c

is not possible.

But is this really the preferred way?

like image 322
Dave Halter Avatar asked Mar 09 '12 19:03

Dave Halter


People also ask

How do I return the last character of a string?

To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.

How do I remove a specific character from a string in Python?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I remove the last 3 characters from a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.


Video Answer


4 Answers

Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split() or separate it into two parts using indices:

a = "abc"
a, result = a[:-1], a[-1]

This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):

for result in reversed(a):
    ...

I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split:

ans = "foo,blah,etc."
for a in ans.split(","):
    ...
like image 148
alexis Avatar answered Oct 17 '22 15:10

alexis


Not only is it the preferred way, it's the only reasonable way. Because strings are immutable, in order to "remove" a char from a string you have to create a new string whenever you want a different string value.

You may be wondering why strings are immutable, given that you have to make a whole new string every time you change a character. After all, C strings are just arrays of characters and are thus mutable, and some languages that support strings more cleanly than C allow mutable strings as well. There are two reasons to have immutable strings: security/safety and performance.

Security is probably the most important reason for strings to be immutable. When strings are immutable, you can't pass a string into some library and then have that string change from under your feet when you don't expect it. You may wonder which library would change string parameters, but if you're shipping code to clients you can't control their versions of the standard library, and malicious clients may change out their standard libraries in order to break your program and find out more about its internals. Immutable objects are also easier to reason about, which is really important when you try to prove that your system is secure against particular threats. This ease of reasoning is especially important for thread safety, since immutable objects are automatically thread-safe.

Performance is surprisingly often better for immutable strings. Whenever you take a slice of a string, the Python runtime only places a view over the original string, so there is no new string allocation. Since strings are immutable, you get copy semantics without actually copying, which is a real performance win.

Eric Lippert explains more about the rationale behind immutable of strings (in C#, not Python) here.

like image 29
Adam Mihalcin Avatar answered Oct 17 '22 16:10

Adam Mihalcin


The precise wording of the question makes me think it's impossible.

return to me means you have a function, which you have passed a string as a parameter.

You cannot change this parameter. Assigning to it will only change the value of the parameter within the function, not the passed in string. E.g.

>>> def removeAndReturnLastCharacter(a):
        c = a[-1]
        a = a[:-1]
        return c

>>> b = "Hello, Gaukler!"
>>> removeAndReturnLastCharacter(b)
!

>>> b    # b has not been changed
Hello, Gaukler!
like image 5
Peter Wood Avatar answered Oct 17 '22 15:10

Peter Wood


Yes, python strings are immutable and any modification will result in creating a new string. This is how it's mostly done.

So, go ahead with it.

like image 1
varunl Avatar answered Oct 17 '22 16:10

varunl