การทำงานกับสตริง

Python เบื้องต้นสำหรับนักพัฒนา

Jasmin Ludolf

Senior Data Science Content Developer

สตริงอยู่ทุกที่!

คำว่า Hello ที่เขียนด้วยสตริง

  • การแสดงข้อความ
  • การประมวลผลข้อความที่ผู้ใช้ป้อน
  • ชื่อไฟล์
  • การจัดรูปแบบผลลัพธ์
  • การจัดการข้อมูล
1 ภาพสร้างโดย ChatGPT
Python เบื้องต้นสำหรับนักพัฒนา

Python รองรับทั้งเครื่องหมายคำพูดเดี่ยวและคู่

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = apostrophe = single quote
Python เบื้องต้นสำหรับนักพัฒนา

ข้อดีของเครื่องหมายคำพูดคู่

# 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
Python เบื้องต้นสำหรับนักพัฒนา

ประโยคและย่อหน้า

recipe_step = "Heat olive oil in a large pan and sauté garlic until fragrant"
Python เบื้องต้นสำหรับนักพัฒนา

สตริงหลายบรรทัด

# 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""": สตริงหลายบรรทัด
    • เพิ่มความอ่านง่าย
    • ใช้สำหรับเอกสาร
    • ข้อความยาว เช่น คำแนะนำหรือข้อความแจ้งข้อผิดพลาด
Python เบื้องต้นสำหรับนักพัฒนา

เมธอด

  • เมธอด = ฟังก์ชันที่ใช้ได้เฉพาะกับชนิดข้อมูลนั้น ๆ

  • เมธอดของ str

    • ทำให้ข้อมูลป้อนเข้าเป็นมาตรฐาน หรือแปลงข้อความ
# Calling a string method
string_variable.method()
Python เบื้องต้นสำหรับนักพัฒนา

การแทนที่ส่วนหนึ่งของสตริง

  • .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
Python เบื้องต้นสำหรับนักพัฒนา

การเปลี่ยนตัวพิมพ์

  • ทำให้ข้อมูลป้อนเข้า เช่น อีเมล เป็นมาตรฐาน
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
Python เบื้องต้นสำหรับนักพัฒนา

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับนักพัฒนา

Preparing Video For Download...