Práce s řetězci

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Řetězce jsou všude!

Nápis Hello vytvořený pomocí řetězce

  • Zobrazování zpráv
  • Zpracování textového vstupu
  • Názvy souborů
  • Formátování výstupu
  • Práce s daty
1 Obrázek vygenerován nástrojem ChatGPT
Introduction to Python for Developers

Python podporuje jednoduché i dvojité uvozovky

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = apostrof = jednoduchá uvozovka
Introduction to Python for Developers

Výhody dvojitých uvozovek

# 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

Věty a odstavce

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

Víceřádkové řetězce

# 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""": Víceřádkové řetězce
    • Zvyšují čitelnost
    • Používají se pro dokumentaci
    • Delší text, např. instrukce nebo chybové zprávy
Introduction to Python for Developers

Metody

  • Metoda = funkce dostupná pouze pro konkrétní datový typ

  • Metody str

    • Standardizace vstupu nebo transformace textu
# Calling a string method
string_variable.method()
Introduction to Python for Developers

Nahrazování částí řetězců

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

Změna velikosti písmen

  • Standardizace uživatelských vstupů, např. e-mailů
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

Vyzkoušejte si to!

Introduction to Python for Developers

Preparing Video For Download...