Do you really think you know strings in Python?
Satwik Kansal (~satwik) |
Description:
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, butprint(r"\ some string \")
raises aSyntaxError
.print('wtfpython''')
is valid butprint("wtfpython""")
raisesSyntaxError
.
Do you know why,
>>> a = "some_string"
>>> id(a)
140420665652016
>>> id("some" + "_" + "string")
140420665652016
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)
0.25748300552368164
# using "+=", three strings:
>>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)
0.012188911437988281
s1 = s1 + s2 + s3
is much slower than s1 += s2 + s3
.
And finally,
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False
# one last attack!
>>> a = "wtf"
>>> b = "wtf"
>>> a is b
True
>>> a = "wtf!"
>>> b = "wtf!"
>>> a is b
False
>>> a, b = "wtf!", "wtf!"
>>> a is b
True
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.
Prerequisites:
Basic familiarity with programming. Prior experience with Python would make the talk more interesting for the attendee.
Content URLs:
Slides: https://speakerdeck.com/satwikkansal/do-you-really-think-you-know-strings-in-python
Also relevant: https://github.com/pydelhi/talks/issues/77
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)