DEV Community

Waylon Walker
Waylon Walker

Posted on • Originally published at waylonwalker.com

9 3

Python string of letters is a string of letters, but not with special

In python, a string is a string until you add special characters.

In browsing twitter this morning I came accross this tweet, that showed that you can use is accross two strings if they do not contain special characters.

I popped open ipython to play with this. I could confirm on 3.9.7, short strings that I typed in worked as expected.

waylonwalker main v3.9.7 ipython
 a = "asdf"

waylonwalker main v3.9.7 ipython
 b = "asdf"

waylonwalker main v3.9.7 ipython
 a is b
True
Enter fullscreen mode Exit fullscreen mode

Using the upper() method on these strings does break down.

waylonwalker main v3.9.7 ipython
 a.upper() is b.upper()
False

waylonwalker main v3.9.7 ipython
 a = "ASDF"

waylonwalker main v3.9.7 ipython
 b = "ASDF"

waylonwalker main v3.9.7 ipython
 a is b
True
Enter fullscreen mode Exit fullscreen mode

If You can also see this in the id of the objects as well, which is the memmory address in CPython.

waylonwalker main v3.9.7 ipython
 id(a)
140717359289568

waylonwalker main v3.9.7 ipython
 id(b)
140717359289568

waylonwalker main v3.9.7 ipython
 id(a.upper())
140717359581824

waylonwalker main v3.9.7 ipython
 id(b.upper())
140717360337824
Enter fullscreen mode Exit fullscreen mode

Finally just as the post shows if you add a special character in there it also breaks.

waylonwalker main v3.9.7 ipython
 a = "ASDF!"

waylonwalker main v3.9.7 ipython
 b = "ASDF!"

waylonwalker main v3.9.7 ipython
 a is b
False
Enter fullscreen mode Exit fullscreen mode

What should you do

First and foremost, these are the exact pitfalls that flake8 guards you against. So the very first things you should take away here is that there is a lot of wisdom and value in flake8.

Second, the is comparison should be used for things that you want to compare to exact memmory addresses. These include booleans and None. Don't use is accross two assigned variables.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more