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?

Daily Life
Interviews
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.
1name = "Alice"
2greeting = 'Hello, World!'
3empty_string = ""
4
5print(name)
6print(greeting)
7print(len(empty_string))
>>>Output
Alice
Hello, World!
0
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:
1message = "She said 'hello' to me"
2contraction = "It's a beautiful day"
3
4print(message)
5print(contraction)
>>>Output
She said 'hello' to me
It's a beautiful day
If you need both types of quotes in the same string, you can use escape sequences or triple quotes. Try picking different quote styles below to see what works.
Fill in the Blank

> 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

An escape sequence is a backslash (\) followed by a character. It tells Python to treat the next character specially. Here are the most common ones:
\'\"\n\t\\
\'
Single quote
Embed apostrophe in text
\"
Double quote
Embed quotes in strings
\n
New line
Creates a line break
\t
Tab character
Inserts tab whitespace
\\
Backslash
Literal backslash char
1quote = "He said \"Python is amazing!\""
2path = "C:\\Users\\Maya\\Documents"
3multiline = "Line 1\nLine 2\nLine 3"

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

For strings that span multiple lines, Python offers triple quotes. These can use either single or double quotes:
1paragraph = """This is a long string that spans multiple lines. Each line break is preserved exactly as you type it."""
Triple-quoted strings preserve all whitespace, including line breaks and indentation. They're commonly used for multi-line text, SQL queries, or documentation strings.

Strings vs Numbers

Daily Life
Interviews

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.

1number = 42
2text = "42"
3
4print(number + 10)
5print(text + "10")
>>>Output
52
4210

The first print outputs 52 (mathematical addition). The second outputs "4210" (string concatenation). The + operator does different things depending on the data types involved.

Number
  • 42 + 10 = 52
  • 42 * 2 = 84
  • Mathematical operations
String
  • "42" + "10" = "4210"
  • "42" * 2 = "4242"
  • Text concatenation
Trying to add a string and a number directly causes an error. See if you can spot and fix the bug below:
Debug Challenge

> 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

Use built-in functions to convert between strings and numbers:
1age_text = "25"
2age = int(age_text)
3print(f"Age: {age}, Next year: {age + 1}")
>>>Output
Age: 25, Next year: 26
You can also convert strings to floating-point numbers and numbers back to strings:
1price_text = "19.99"
2price = float(price_text)
3print(price)
4
5score = 100
6message = "Score: " + str(score)
7print(message)
>>>Output
19.99
Score: 100

str() converts any value to its string representation. int() and float() convert strings to numbers (if the string contains valid numeric characters).

01
str()
Converts any value to its text representation. Works on ints, floats, bools, and more.
02
int()
Converts a string of digits to a whole number. Raises ValueError if the string is not numeric.
03
float()
Converts a string to a decimal number. Accepts digits with a decimal point.

String Concatenation

Daily Life
Interviews

Concatenation means joining strings together. The + operator combines two strings into one, placing them end-to-end.

1first_name = "Maya"
2last_name = "Johnson"
3
4full_name = first_name + " " + last_name
5print(full_name)
>>>Output
Maya Johnson
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:
1product = "Laptop"
2price = 999.99
3quantity = 2
4
5message = "Order: " + str(quantity) + "x " + product + " at $" + str(price)
6print(message)
>>>Output
Order: 2x Laptop at $999.99

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:

1divider = "-" * 40
2print(divider)
3
4echo = "Hello! " * 3
5print(echo)
>>>Output
----------------------------------------
Hello! Hello! Hello!
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.
Fill in the Blank

> 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)
TIP
While + 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()

Daily Life
Interviews

The len() function returns the number of characters in a string. It counts every character, including spaces and punctuation.

1message = "Hello, World!"
2length = len(message)
3print(length)
>>>Output
13
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:
1empty = ""
2print(len(empty))
3
4space_only = " "
5print(len(space_only))
>>>Output
0
3
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()

len() is commonly used for validation and loop control:

1password = "secret123"
2
3if len(password) < 8:
4 print("Password too short!")
5else:
6 print("Password length OK")
>>>Output
Password length OK
This validates that a password has at least 8 characters. Length checking is essential for input validation, truncation, and many other string operations.
Checking if a string is empty:
1user_input = ""
2
3if len(user_input) == 0:
4 print("No input provided")
5
6# More Pythonic way:
7if not user_input:
8 print("No input provided")
>>>Output
No input provided
No input provided

Both approaches work. The second is more "Pythonic" because empty strings are falsy in Python (they evaluate to False in boolean contexts).

Python Quiz

> 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))
str
<=
len
==
type

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.

TIP
For multi-condition validation such as checking both minimum and maximum length, Python allows chained comparisons: 3 <= len(username) <= 10 reads naturally and evaluates correctly without repeating len(username).

Case Conversion

Daily Life
Interviews
Python provides methods to change the case of strings. These are essential for normalizing user input and performing case-insensitive comparisons.

lower() and upper()

.lower() converts all letters to lowercase. .upper() converts all letters to uppercase. Neither method affects non-letter characters.

1text = "Hello, World!"
2
3print(text.lower())
4print(text.upper())
5print(text)
>>>Output
hello, world!
HELLO, WORLD!
Hello, World!
This prints "hello, world!", then "HELLO, WORLD!", then the original "Hello, World!". The original string is unchanged because strings are immutable in Python.
TIP
String methods return new strings. They don't modify the original. If you want to keep the result, assign it to a variable: lower_text = text.lower()

Other Case Methods

Python provides several case-related methods for different formatting needs:
.capitalize().title().swapcase()
.capitalize()
First letter up
Rest becomes lowercase
.title()
Title Case
Each word capitalized
.swapcase()
Swap all case
Upper becomes lower etc
1name = "aLiCe JoHnSoN"
2
3print(name.capitalize())
4print(name.title())
5print(name.swapcase())
>>>Output
Alice johnson
Alice Johnson
AlIcE jOhNsOn

Outputs: "Alice johnson", "Alice Johnson", and "AlIcE jOhNsOn" respectively. The title() method is especially useful for formatting names and headings.

Case-Insensitive Comparing

A common use case is comparing strings regardless of case. Try selecting different case methods below to see which ones produce a match:
Fill in the Blank

> 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

You can check if a string is in a particular case:
1text1 = "HELLO"
2text2 = "hello"
3text3 = "Hello World"
4
5print(text1.isupper())
6print(text2.islower())
7print(text3.istitle())
>>>Output
True
True
True
All three print True. These methods are useful for validation, such as checking if a username meets case requirements.

Strings Are Immutable

A fundamental property of Python strings: they cannot be changed after creation. This is called immutability. When you "modify" a string, you're actually creating a new string.
1name = "Alice"
2name = name.upper()
3print(name)
>>>Output
ALICE

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.

You cannot change individual characters in a string:
1text = "Hello"
2text[0] = "J"

This raises a TypeError. To "change" a character, you must create a new string:

1text = "Hello"
2new_text = "J" + text[1:]
3print(new_text)
>>>Output
Jello

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.

Safe as dictionary keys
Safe as dictionary keys
Immutable objects can be hashed and used as dictionary keys reliably.
Safe variable sharing
Safe variable sharing
Multiple variables can point to the same string without risk of accidental changes.
String interning
String interning
Python can reuse identical string objects in memory to save space.
Immutability enables a neat optimization under the hood.
Because strings are immutable, every method that appears to modify a string actually returns a new one.
STRING IMMUTABILITY RULES
  • 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

Here are the most common string-related mistakes beginners make. Study these patterns to avoid them in your own code:
Do
  • "Total: " + str(100)
  • text = text.upper()
  • if answer.lower() == "yes":
Don't
  • "Total: " + 100
  • text.upper() # discarded!
  • if answer == "yes":
The first mistake is forgetting to convert types before concatenating. The second is forgetting to save the return value of a string method. The third is doing case-sensitive comparisons on user input.
TIP
When a string method "doesn't work," check if you forgot to assign the result. Since strings are immutable, methods always return new strings.
Practice spotting the most common immutability mistake. The code below calls a string method but forgets to save the result.
Debug Challenge

> 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

Forgetting to save a string method result is one of the most common Python beginner mistakes because the method call looks like it should work in place. Since strings are immutable, every method returns a new string and the original is never changed.

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.

TIP
Whenever a string method produces no visible effect, check two things: did you assign the result back, and did you print the right variable? These two checks solve the vast majority of "string method not working" issues.
PUTTING IT ALL TOGETHER

> 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.

upper() and lower() normalize text case so "alice@email.com" and "ALICE@EMAIL.COM" are recognized as the same address during deduplication.
strip() removes leading and trailing whitespace that causes silent mismatch failures when joining records across source systems.
String concatenation combines first and last name fields plus formatting characters into the single display name the CRM expects.
len() validates that required fields like phone numbers and postal codes contain the expected number of characters before insertion.
KEY TAKEAWAYS
Strings are sequences of characters enclosed in single or double quotes
Use + to concatenate strings, * to repeat them
len() returns the number of characters in a string
.lower() and .upper() convert case (returning new strings)
Always convert numbers to strings with str() before concatenating
Strings are immutable - methods return new strings, not modify originals
Use .lower() for case-insensitive comparisons

Text 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

  1. 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

  2. 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:

  3. 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.

  4. 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

  5. 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