Working with strings

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Strings are everywhere!

Hello written with string

  • Displaying messages
  • Processing text input
  • File names
  • Formatting output
  • Handling data
1 Image generated by ChatGPT
Introduction to Python for Developers

Python knows single and double quotes

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = apostrophe = single quote
Introduction to Python for Developers

Advantages of double quotes

# Single quote string variable containing an apostrophe
ingredient_name = 'Chef's special seasoning'
print(ingredient_name)
SyntaxError: invalid syntax.
# Double quote string variable containing an apostrophe
ingredient_name = "Chef's special seasoning"
print(ingredient_name)
Chef's special seasoning
Introduction to Python for Developers

Sentences and paragraphs

recipe_step = "Heat olive oil in a large pan and sauté garlic until fragrant"
Introduction to Python for Developers

Multi-line strings

# Create a string variable over multiple lines
recipe_instructions = """1. Bring a large pot of salted water to boil and cook pasta
2. Heat olive oil in a pan and sauté minced garlic until fragrant
3. Add chopped tomatoes and simmer for 10 minutes
4. Toss cooked pasta with tomato sauce and fresh basil leaves
"""
  • """text""": Multi-line strings
    • Enhance readability
    • Used for documentation
    • Longer text such as instructions or error messages
Introduction to Python for Developers

Methods

  • Method = a function that is only available to a specific data type

  • str methods

    • Standardizing input, or transforming text
# Calling a string method
string_variable.method()
Introduction to Python for Developers

Replacing parts of strings

  • .replace(text_to_be_replaced, text_to_change_it_to)
welcome_message = "Welcome to the recipe scaler, George"

welcome_message = welcome_message.replace("George", "John")

print(welcome_message)
Welcome to the recipe scaler, John
Introduction to Python for Developers

Changing case

  • Standardize user inputs like emails
ingredient_name = "Basil Leaves"

# Convert to lowercase ingredient_name = ingredient_name.lower() print(ingredient_name)
basil leaves
# Change to uppercase
ingredient_name = ingredient_name.upper()
print(ingredient_name)
BASIL LEAVES
Introduction to Python for Developers

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...