Strings: Beginner
Twilio processes billions of SMS messages every year, and every automated text you receive from a bank, airline, or delivery service likely passed through string operations on its way to your phone. Parsing the phone number from an inbound message, extracting a keyword to decide which response to send, stripping whitespace from user input, and converting text to a consistent case for routing are all foundational string operations that run inside Twilio's platform millions of times per hour. The string creation, indexing, slicing, and basic methods you learn in this lesson are the exact tools that make programmable messaging possible.
What is a String?
Choosing Quote Styles
> You need to store the text "It's Python" in a variable, but the apostrophe could conflict with your quote characters. Pick opening and closing quotes that avoid a syntax error.
text = It's Python print(text)
Escape Sequences
The \n escape sequence creates a new line. When you print the multiline string above, it will display on three separate lines.
Triple-Quoted Strings
Strings vs Numbers
A critical concept in Python: the string "42" is completely different from the number 42. They look similar when printed, but they behave differently in your code.
The first print outputs 52 (mathematical addition). The second outputs "4210" (string concatenation). The + operator does different things depending on the data types involved.
- 42 + 10 = 52
- 42 * 2 = 84
- Mathematical operations
- "42" + "10" = "4210"
- "42" * 2 = "4242"
- Text concatenation
> This code tries to concatenate a string with the integer 100 using the + operator, but Python cannot add a str and an int together.
TypeError: can only concatenate str to str
Converting Between Types
str() converts any value to its string representation. int() and float() convert strings to numbers (if the string contains valid numeric characters).
String Concatenation
Concatenation means joining strings together. The + operator combines two strings into one, placing them end-to-end.
Building Complex Strings
This outputs: "Order: 2x Laptop at $999.99". Notice how we converted numbers to strings with str() before concatenating.
String Repetition
The * operator repeats a string a specified number of times:
> You have the string "Ha" and want to either concatenate it with another string or repeat it multiple times. Pick an operator and a second operand to see the result.
result = "Ha" print(result)
+ concatenation works, f-strings (formatted string literals) are often cleaner for complex strings. We'll cover f-strings in the intermediate lesson.String concatenation with + builds new strings by joining two existing ones end-to-end. Each + operation creates a brand new string object. For joining many strings in a loop, this can be slow; using "".join(list_of_strings) is far more efficient for bulk assembly.
The * operator repeats a string a fixed number of times, which is useful for generating separators, padding, or simple repeated patterns without writing a loop.
String Length with len()
The len() function returns the number of characters in a string. It counts every character, including spaces and punctuation.
Empty Strings
Practical Uses of len()
len() is commonly used for validation and loop control:
Both approaches work. The second is more "Pythonic" because empty strings are falsy in Python (they evaluate to False in boolean contexts).
> A username is checked for validity: it must be at least 3 characters and no more than 10. Pick the correct function to measure the string length, and the correct comparison operator for the maximum check.
username = "alice" n = (username) if n >= 3 and n 10: print("Valid") else: print("Invalid") print(len(username))
len() is one of Python's most-used built-in functions for strings. It counts every character including spaces, punctuation, and newline characters. Understanding the exact count is important for validation, truncation, and formatted output.
Empty strings have length 0 and are falsy in Python, so if not user_input: is an idiomatic way to check for an empty string. Both len(s) == 0 and not s are correct, but the latter is considered more Pythonic.
Case Conversion
lower() and upper()
.lower() converts all letters to lowercase. .upper() converts all letters to uppercase. Neither method affects non-letter characters.
Other Case Methods
Outputs: "Alice johnson", "Alice Johnson", and "AlIcE jOhNsOn" respectively. The title() method is especially useful for formatting names and headings.
Case-Insensitive Comparing
> A user typed "YES" but your code compares against the lowercase string "yes". Pick a case method to normalize the input so the comparison succeeds.
answer = "YES" if answer.() == "yes": print("Match!")
Checking Case
Strings Are Immutable
This does not change the original "Alice" string. Instead, it creates a new string "ALICE" and assigns it to the variable name. The original "Alice" string still exists in memory until Python removes it.
This raises a TypeError. To "change" a character, you must create a new string:
This creates "Jello" by concatenating "J" with everything from position 1 onward using the slice text[1:]. We'll cover string slicing in detail in the intermediate lesson.
- String methods always return NEW strings
- You must assign the result: text = text.upper()
- Individual characters cannot be changed in place
- Use concatenation or slicing to build modified strings
Common Mistakes to Avoid
- "Total: " + str(100)
- text = text.upper()
- if answer.lower() == "yes":
- "Total: " + 100
- text.upper() # discarded!
- if answer == "yes":
> This code calls .upper() on a name string but never saves the return value. Since strings are immutable, the original variable stays lowercase.
Prints "alice" instead of "ALICE" because the result of .upper() is not saved
Case conversion methods like upper(), lower(), and title() are frequently used to normalize user input before comparison. Comparing answer.lower() == "yes" correctly matches "YES", "Yes", and "yes" without needing separate conditions.
> You are a data analyst at HubSpot cleaning messy customer name and email fields pulled from three different source systems before merging them into the master contact database.
+ to concatenate strings, * to repeat themlen() returns the number of characters in a string.lower() and .upper() convert case (returning new strings)str() before concatenating.lower() for case-insensitive comparisonsText is everywhere in programming
- Category
- Python
- Difficulty
- beginner
- Duration
- 31 minutes
- Challenges
- 0 hands-on challenges
Topics covered: What is a String?, Strings vs Numbers, String Concatenation, String Length with len(), Case Conversion
Lesson Sections
- What is a String? (concepts: pyStringBasic)
A string is a sequence of characters. It can contain letters, numbers, spaces, punctuation, and special symbols. In Python, strings are created by enclosing text in quotes. Python does not care whether you use single quotes (') or double quotes ("). Both create the same type of string. Choose the style that makes your code more readable. Choosing Quote Styles The main advantage of having two quote styles is that you can include one type of quote inside a string wrapped with the other: If you nee
- Strings vs Numbers
Trying to add a string and a number directly causes an error. See if you can spot and fix the bug below: Converting Between Types Use built-in functions to convert between strings and numbers: You can also convert strings to floating-point numbers and numbers back to strings:
- String Concatenation
This prints "Maya Johnson". Notice we added a space " " between the names. Without it, we'd get "MayaJohnson". Building Complex Strings You can concatenate as many strings as needed to build formatted output: String Repetition The first line creates a string of 40 dashes. The second repeats "Hello! " three times. This is useful for creating visual separators or repeated patterns.
- String Length with len()
This prints 13. The string has 13 characters: 5 letters in "Hello", a comma, a space, 5 letters in "World", and an exclamation mark. Empty Strings An empty string "" has length 0. It's a valid string that happens to contain no characters: The first prints 0. The second prints 3 because spaces count as characters. An empty string and a string of spaces are different! Practical Uses of len() This validates that a password has at least 8 characters. Length checking is essential for input validation
- Case Conversion
Python provides methods to change the case of strings. These are essential for normalizing user input and performing case-insensitive comparisons. lower() and upper() This prints "hello, world!", then "HELLO, WORLD!", then the original "Hello, World!". The original string is unchanged because strings are immutable in Python. Other Case Methods Python provides several case-related methods for different formatting needs: Case-Insensitive Comparing A common use case is comparing strings regardless