Creating Strings
Introduction
In Python, strings can be created in several ways. While creating strings is trivial, knowing when to use specific string creation methods can save you time and prevent bugs during interviews.
Single and Double Quotes
Python allows strings to be enclosed in either single quotes (') or double quotes (").
When to use which?
Use whichever prevents you from needing to escape characters.
If your string contains a single quote (like an apostrophe), use double quotes to enclose the string.
Multi-line Strings
Use triple quotes (''' or """) for strings that span multiple lines.
In interviews, multi-line strings are rarely needed unless you are hardcoding a multiline test case or an ASCII grid.
Converting Other Types to Strings
You will frequently need to convert integers, lists, or other data structures into strings.
Using str()
The str() built-in function converts an object into its string representation.
Common Interview Mistake: str() on Lists
Beginners sometimes try to convert a list of characters back into a string using str().
Incorrect:
Output:
This includes the brackets and commas as part of the string!Correct:
Use "".join() to convert a list of characters or strings into a single string.
Time and Space Complexity
- Time Complexity: \(O(N)\) where \(N\) is the length of the string being created or the object being converted.
- Space Complexity: \(O(N)\) to store the newly created string.
Summary
- Single and double quotes are functionally identical.
- Always use
"".join()instead ofstr()when converting a list of characters back into a single string.