...

/

Strings Can Be Tricky Sometimes

Strings Can Be Tricky Sometimes

We'll cover the following...

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

1.

Notice that both the ids are the same.

Press + to interact
a = "some_string"
print(id(a))
print(id("some" + "_" + "string"))

2.

Let's see if you can explain the behavior of the following code:
Press + to interact
>>> 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:
Press + to interact
>>> 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.

Press + to interact
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.

Press + to interact
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 ...

svg viewer