Praca z łańcuchami znaków

Wprowadzenie do Pythona dla programistów

Jasmin Ludolf

Senior Data Science Content Developer

Łańcuchy znaków są wszędzie!

Napis Hello jako łańcuch znaków

  • Wyświetlanie komunikatów
  • Przetwarzanie tekstu
  • Nazwy plików
  • Formatowanie wyników
  • Obsługa danych
1 Obraz wygenerowany przez ChatGPT
Wprowadzenie do Pythona dla programistów

Python obsługuje oba rodzaje cudzysłowów

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = apostrof = pojedynczy cudzysłów
Wprowadzenie do Pythona dla programistów

Zalety podwójnych cudzysłowów

# 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
Wprowadzenie do Pythona dla programistów

Zdania i akapity

recipe_step = "Heat olive oil in a large pan and sauté garlic until fragrant"
Wprowadzenie do Pythona dla programistów

Łańcuchy wieloliniowe

# 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""": Łańcuchy wieloliniowe
    • Lepsza czytelność
    • Używane w dokumentacji
    • Dłuższy tekst, np. instrukcje lub komunikaty błędów
Wprowadzenie do Pythona dla programistów

Metody

  • Metoda = funkcja dostępna tylko dla określonego typu danych

  • Metody str

    • Standaryzacja danych wejściowych lub przekształcanie tekstu
# Calling a string method
string_variable.method()
Wprowadzenie do Pythona dla programistów

Zastępowanie fragmentów łańcuchów

  • .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
Wprowadzenie do Pythona dla programistów

Zmiana wielkości liter

  • Standaryzacja danych wejściowych, np. adresów 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
Wprowadzenie do Pythona dla programistów

Czas na ćwiczenia!

Wprowadzenie do Pythona dla programistów

Preparing Video For Download...