String Tips

Learn how to format strings in a Pythonic way.

Do not str() a str variable

The str(x) function is a string constructor, converting whatever x is into a string. This function never fails, but doesn’t always do what we expect and isn’t always needed.

  • The function is not useful when applied to compound data structures such as lists, dictionaries, sets, and generators. It displays either too many details or too few of them.
  • The function also isn’t needed when x is already a string.

Converting a string to a string doesn’t change the string but takes some time.

Get hands-on with 1200+ tech skills courses.