KAHIBARO Bookshelves
Discord Login Register

3.4. Test

Why Text Matters in Programs

In many programs, you don’t only work with numbers—you also work with words, sentences, names, messages, and other text. In Python, pieces of text are stored in a data type called a string, written as str (short for “string”).

A string can hold anything you can type on a keyboard: letters, digits, spaces, punctuation, and even symbols.

Creating Strings

You create a string by putting text inside quotes. You can use either single quotes ' or double quotes ".

message = "Hello, world!"
name = 'Alice'
address = "221B Baker Street"
number_as_text = "12345"   # This is text, NOT a number

Python doesn’t care whether you use single or double quotes, but they must match: open and close with the same type.

This is valid:

greeting = "Hello"
reply = 'Hi'

This is not valid (unmatched quotes):

# This will cause a SyntaxError
wrong = "Hello'

Empty Strings

You can also create an “empty” string with nothing inside the quotes:

empty1 = ""
empty2 = ''

An empty string is still a string; it just has length $0$ (no characters).

Strings Are Sequences of Characters

A string is a sequence (ordered collection) of characters. Each character has a position (index), starting from $0$.

For the string:

word = "Python"

The characters and their positions are:

  • P → index $0$
  • y → index $1$
  • t → index $2$
  • h → index $3$
  • o → index $4$
  • n → index $5$

Python lets you access individual characters using square brackets []:

word = "Python"
first_letter = word[0]
third_letter = word[2]
print(first_letter)   # P
print(third_letter)   # t

Trying to use an index that is too large will cause an error, because there is no character at that position.

Basic String Operations

You’ll see some of these operations again in more detail later, but here are the most common things you can do with str.

String Concatenation (Joining Text)

You can join strings together using the + operator. This is called concatenation.

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)   # Ada Lovelace

Important: + for strings only works between strings. You can’t directly + a string and a number.

This will cause an error:

age = 30
text = "I am " + age   # TypeError

You’ll see later how to combine text and numbers safely in another chapter.

Repeating Strings

You can repeat a string using * and an integer.

laugh = "ha"
print(laugh * 3)   # hahaha
line = "-" * 40
print(line)        # ----------------------------------------

The number must be an integer (int). You cannot multiply by a string or a float.

Special Characters and Escape Sequences

Sometimes you need characters that are hard to type directly inside a string, like a newline (go to the next line) or an actual quote character inside quotes.

Python uses escape sequences, which start with a backslash \.

Common escape sequences:

  • Newline: \n
  • Tab: \t
  • Single quote inside single quotes: \'
  • Double quote inside double quotes: \"
  • Backslash itself: \\
text = "First line\nSecond line"
print(text)
# Output:
# First line
# Second line
path = "C:\\Users\\Alice"
print(path)  # C:\Users\Alice

Quotes Inside Strings

If you want quotes inside a string, you have two main options.

  1. Use different quotes outside and inside:
sentence1 = "It's a sunny day"
sentence2 = 'He said, "Hello!"'
  1. Escape the quotes:
sentence3 = 'It\'s a sunny day'
sentence4 = "He said, \"Hello!\""

Both approaches are common; choose whichever is clearer.

Multiline Strings

If you want a string that spans several lines, you can use triple quotes: """ or '''.

text = """This is a
multiline string.
It has three lines."""
print(text)

Python keeps the line breaks as part of the string.

Multiline strings are also often used for long messages or documentation.

Checking the Type of a String

To confirm that a value is a string, you can use type():

message = "Hello"
print(type(message))    # <class 'str'>
print(type("123"))      # <class 'str'>

Even if a string looks like a number, it is still of type str if it’s inside quotes.

Length of a String

You can find out how many characters are in a string using len():

word = "Python"
print(len(word))   # 6
empty = ""
print(len(empty))  # 0
phrase = "Hello, world!"
print(len(phrase)) # 13

Spaces and punctuation are counted as characters too.

Basic String Methods

Strings come with built-in methods (actions you can perform on them). You call a method with a dot . after the string.

Some useful beginner-friendly methods:

Changing Case: `lower()` and `upper()`

  • lower() → returns a version of the string with all letters in lowercase
  • upper() → returns a version with all letters in uppercase
name = "Alice"
print(name.lower())  # alice
print(name.upper())  # ALICE

Note: These methods create new strings; they do not change the original:

name = "Alice"
lower_name = name.lower()
print(name)       # Alice
print(lower_name) # alice

Removing Extra Spaces: `strip()`

strip() removes spaces (and some other whitespace) from the beginning and end of a string.

raw = "   hello   "
cleaned = raw.strip()
print(raw)      # '   hello   '
print(cleaned)  # 'hello'

There are also lstrip() (left only) and rstrip() (right only).

Finding Substrings: `in`

You can check if one string is contained inside another using the keyword in, which returns a Boolean value (True or False):

sentence = "Python is fun"
print("Python" in sentence)  # True
print("Java" in sentence)    # False

Converting Between Strings and Other Types (Overview)

Strings are often used to store user input, which arrives as text. Sometimes you need to convert between strings and numbers.

A quick overview (there is a full chapter later on conversions):

  • Convert number → string: str()
  • Convert string with digits → integer: int()
  • Convert string with digits and a decimal point → float: float()
age = 30
age_text = str(age)        # "30"
number_text = "42"
number_value = int(number_text)   # 42

If the text does not look like a number, int() or float() will cause an error.

Common Beginner Mistakes with Strings

1. Forgetting Quotes

Without quotes, Python thinks something is a variable name, not text.

# This will cause a NameError
message = Hello

Correct:

message = "Hello"

2. Mixing Numbers and Strings with `+` Directly

age = 25
# This will cause a TypeError
text = "I am " + age

You need to convert the number or use another method (covered later):

text = "I am " + str(age)

3. Using the Wrong Quotes

# SyntaxError: EOL while scanning string literal
text = "She said, "Hi!""

Fix by changing outer quotes or escaping inner quotes:

text = 'She said, "Hi!"'
# or
text = "She said, \"Hi!\""

Simple Practice Ideas

Here are a few small things you can try to get comfortable with str:

  1. Store your full name in a variable and print:
    • Your name in all lowercase
    • Your name in all uppercase
    • The length of your name using len()
  2. Create a string with a sentence, then:
    • Check whether your first name appears in the sentence using in.
    • Print the sentence on two lines using \n.
  3. Make a small “divider” line using *:
line = "=" * 30
print(line)

This chapter’s goal is for you to be comfortable creating and using text values (str) in Python—storing them in variables, joining them, and doing simple operations with them.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms