Do you really think you know strings in Python?

Satwik Kansal (~satwik)




Do you know that,

  • 'a'[0][0][0][0][0] is a semantically valid statement in Python.
  • print(r"\ some string") is a valid statement, but print(r"\ some string \") raises a SyntaxError.
  • print('wtfpython''') is valid but print("wtfpython""") raises SyntaxError.

Do you know why,

>>> a = "some_string"
>>> id(a)
>>> id("some" + "_" + "string")

the id of both the objects in above snippet is same?

And do you know why,

>>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)
# using "+=", three strings:
>>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)

s1 = s1 + s2 + s3 is much slower than s1 += s2 + s3.

And finally,

>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'

# one last attack!
>>> a = "wtf"
>>> b = "wtf"
>>> a is b

>>> a = "wtf!"
>>> b = "wtf!"
>>> a is b

>>> a, b = "wtf!", "wtf!"
>>> a is b

Do you know the reason behind all the above-discussed facts and snippets? Some of them are really puzzling, right? I felt the same when I first came across all these intricacies.

But don't worry, such behaviors, are mostly the consequences of strings being [immutable] [sequences] in Python. In this talk we'll be going through the concepts behind such snippets in detail, so that next time when you see such examples, the answer seems natural to you.

Finally, we'll try to answer some interesting questions like,

  • How does string concatenation work?
  • What's the best way of building large strings in Python? (It may actually depend on your use-case)
  • What happens when you multiply a string by a boolean?
  • How strings in Python differ from strings in other languages like JavaScript, C++?

and many more.


Basic familiarity with programming. Prior experience with Python would make the talk more interesting for the attendee.

Content URLs:


Also relevant:

Most of the snippets and concepts to be discussed are taken from various resources I came across during my 6 months long research about Python. I have collected such snippets in a project called "What the f*ck Python!". Here's the source:

Speaker Info:

I'm a Software Developer experienced with Decentralized Applications and Data Science. In my leisure time, I love doing pointless things with programming. Currently on a quest to learn as much as I could about Computer Science. And lastly, I prefer all things Python! (A humble brag)

Speaker Links:

Website | Github | Archives

Past Speaking Experience

  • PyCon India 2017 (Speaker for a DevSprint)
  • EuroPython 2017 (Invited as a Speaker for a workshop, unable to attend though)
  • IWD-Delhi 2018 (Speaker)
  • PyDelhi biweekly meetup (Gave a small talk)
  • OSS DTU (Instructor and moderator)

Id: 694
Section: Core python and Standard library
Type: Talks
Target Audience: Intermediate
Last Updated: