I tried to use the .strip() command to eliminate white spaces from a string variable and then print it. The white spaces were not removed. Can someone explain why the strip() command isn’t working where I’m going wrong and what is the right way to use this command?
Please don’t post screen shots. If you read some of the content here, you’ll understand why.
I can’t read your code, but…
string = " This is a string "
print(len(string))
print(len(string.strip()))
What’s not working here?
strip()
method doesn’t update the string. It creates a new string.
Please don’t post pictures. There is copy available in any text editor and paste between code tags here works just fine.
Why you say that strip doesn’t work. I can see that you actually managed to print string with stripped whitespace. Strings are immutable so your first attempts were not supposed to work.
NB! There is difference between Python interactive interpreter and running the file.
Thanks @sandraC and @aivarpaalberg
if one checks for,
str.__init__.__qualname__
outputs,
'object.__init__'
if one checks,
for i in [tuple, str, list, dict, set, frozenset, int, float, complex]:
print(i, i.__init__.__qualname__)
outputs,
<class 'tuple'> object.__init__
<class 'str'> object.__init__
<class 'list'> list.__init__
<class 'dict'> dict.__init__
<class 'set'> set.__init__
<class 'frozenset'> object.__init__
<class 'int'> object.__init__
<class 'float'> object.__init__
<class 'complex'> object.__init__
maybe for immutable data types, the __init__
actually means, object.__init__
if we look in the cpython implementation for object.__init__
, maybe it is here, (I am not sure about this though, I searched for __init__
in object.c, and there was no result)
(I did put a printf statement there, but it did not get called)
which calls,
which calls,
but how exactly is a particular data type made immutable is confusing to me.
@vainaixr : Please use a new thread when asking about something not related to the current one.
To answer you question: in the end there’s nothing special about immutable types, other than that the implementation of these types don’t provide operations to update instances (for example, tuple() does not implement __setitem__
).
Locking old topic that seems to have been answered.