...

/

Strings Can Be Tricky Sometimes

Strings Can Be Tricky Sometimes

Let’s see how to use strings correctly in Python.

1.

Notice that both the ids are the same.

Python 3.5
a = "some_string"
print(id(a))
print(id("some" + "_" + "string"))

2.

Let's see if you can explain the behavior of the following code:
>>> a = "ftw"
>>> b = "ftw"
>>> a is b
True # output
>>> a = "ftw!"
>>> b = "ftw!"
>>> a is b
False

Try it out in the terminal below:

Terminal 1
Terminal
Loading...

3.

Let's try something new:
>>> a, b = "ftw!", "ftw!"
>>> a is b # All versions except 3.7.x
True
>>> a = "ftw!"; b = "ftw!"
>>> a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)
True

Try it out in the terminal below:

Terminal 1
Terminal
Loading...

This time, try in the file main.py.

Python 3.5
a = "ftw!"; b = "ftw!"
print(a is b)
# prints True when the module is invoked!

3.

Let's see if you can predict the output of the following code.

⚠️ The following code is meant for < Python 2.x versions.

Python 3.5
print('a' * 20 is 'aaaaaaaaaaaaaaaaaaaa')
print('a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa')

Explanation

  • The behavior in the first and second snippets is due to a CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. ...

svg viewer