Arbeta med strängar

Introduktion till Python för utvecklare

Jasmin Ludolf

Senior Data Science Content Developer

Strängar finns överallt!

Hello skrivet med en sträng

  • Visa meddelanden
  • Bearbeta textinmatning
  • Filnamn
  • Formatera utdata
  • Hantera data
1 Bild genererad av ChatGPT
Introduktion till Python för utvecklare

Python förstår enkla och dubbla citattecken

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = apostrof = enkelt citattecken
Introduktion till Python för utvecklare

Fördelarna med dubbla citattecken

# 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
Introduktion till Python för utvecklare

Meningar och stycken

recipe_step = "Heat olive oil in a large pan and sauté garlic until fragrant"
Introduktion till Python för utvecklare

Flerlradssträngar

# 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""": Flerlradssträngar
    • Förbättrar läsbarheten
    • Används för dokumentation
    • Längre text, t.ex. instruktioner eller felmeddelanden
Introduktion till Python för utvecklare

Metoder

  • Metod = en funktion som bara är tillgänglig för en specifik datatyp

  • str-metoder

    • Standardisera inmatning eller omvandla text
# Calling a string method
string_variable.method()
Introduktion till Python för utvecklare

Ersätta delar av strängar

  • .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
Introduktion till Python för utvecklare

Ändra skiftläge

  • Standardisera användarinmatning som e-postadresser
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
Introduktion till Python för utvecklare

Nu kör vi en övning!

Introduktion till Python för utvecklare

Preparing Video For Download...