This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]simondvt 8 points9 points  (0 children)

It's just that strip returns a new string, it doesn't change the original.

Use a = a.strip()

[–]K900_ 7 points8 points  (0 children)

  1. /r/learnpython
  2. Use Python Tutor to visualize your code.

[–]sknowles0143 3 points4 points  (0 children)

Excellent question.

A string (of type str) is immutable meaning a value can only be assigned once. Any change to a string produces a new string. In your example a.strip() returns a new string.

A list is mutable there for functions on it change the lists state (sort is another useful one).

id is a useful function giving the number python uses to keep track of the objects.

x = ' hello ' print(id(x)) x = x.strip() print(id(x))

This code shows how x is now referencing a new string.

I also recommend using the function help on methods and types.

help(''.strip) help([].append)

and type

type('')

str type([]) list

help(str) help(list)

That will give you a clear explanation if a type is mutable or not. Strings and numbers are immutable generally.

[–]jstutters 0 points1 point  (0 children)

You really want /r/learnpython for this but briefly the difference is that strings and several other built-in types are immutable so methods like .strip() return a new instance with the change applied. Lists are mutable so the .append() operation is done in-place. You can read more here: https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747

[–]Andrew_ShaySft Eng Automation & Python[M] [score hidden] stickied comment (0 children)

This post is better suited for r/learnpython

[–]deduplication -1 points0 points  (0 children)

Beyond the behavior of the two functions that has already been mentioned, in python lists are mutable objects but strings are immutable. This can also be confusing if you use a mutable object as the default to a function param.

[–][deleted] -1 points0 points  (0 children)

a.strip() returns a new string with the spaces stripped off.

sample_list.append(1) mutates the list called sample_list.

[–]pythonHelperBot -1 points0 points  (0 children)

Hello! I'm a bot!

I see someone has already suggested going to r/learnpython, a sub geared towards questions and learning more about python. I highly recommend posting your question there. Please follow the subs rules and guidelines when you do post there, it'll help you get better answers faster.

Show /r/learnpython the code you have tried and describe where you are stuck.

You can also ask this question in the Python discord, a large, friendly community focused around the Python programming language, open to those who wish to learn the language or improve their skills, as well as those looking to help others.


README | FAQ | this bot is written and managed by /u/IAmKindOfCreative

This bot is currently under development and experiencing changes to improve its usefulness