Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Strings: คู่มือครบวงจร สร้าง, Manipulate, Format และ Best Practices

String ใน Python เป็น Immutable Sequence ของ Unicode Characters มี Method หลากหลายสำหรับจัดการข้อความ

1. สร้าง String ใหม่

# Single/Double quotes - เท่ากัน
double_quotes = "My name is John!"
single_quotes = 'My name is John!'

# Triple quotes - Multi-line string
multi_line = '''Line 1
Line 2
Line 3'''

# Raw string - ไม่ escape characters (regex, paths)
raw = r"C:\Users\John\Documents"

2. Indexing และ Slicing

text = "Python"

# Positive Index: 0 1 2 3 4 5
# Negative Index: -6 -5 -4 -3 -2 -1

text[0]    # 'P'
text[2]    # 't'
text[-1]   # 'n' (last)
text[-3]   # 'h'

# Slicing: [start:stop:step] - stop ไม่รวม
text[1:4]   # 'yth' (index 1,2,3)
text[:3]    # 'Pyt' (จากต้น)
text[3:]    # 'hon' (ถึงท้าย)
text[::2]   # 'Pto' (ทีละ 2)
text[::-1]  # 'nohtyP' (กลับลำดับ!)

3. Properties และ Basic Operations

text = "Hello World"

len(text)           # 11 - ความยาว
"Hello" in text     # True - membership test
"Hi" not in text    # True

4. Iterate String

for char in "John":
    print(char)
# J
# o
# h
# n

5. String Concatenation (ต่อ String)

str1 = "Hello"
str2 = "World"

# + operator
str1 + str2           # "HelloWorld"
str1 + " " + str2     # "Hello World"

# * operator - repeat
str1 * 3              # "HelloHelloHello"

# join() - แนะนำสำหรับหลาย strings
words = ["Hello", "World"]
" ".join(words)       # "Hello World"
",".join(words)       # "Hello,World"

💡 Performance Tip: ใช้ join() สำหรับต่อ String หลายตัว (O(n)) แทน + ใน Loop (O(n²))

6. String + Number Concatenation

name = "John"
age = 35

# ❌ Error: can only concatenate str to str
# print(name + age)

# ✅ แปลงก่อน
print(name + str(age))        # "John35"
print(f"{name} {age}")        # "John 35" - f-string (แนะนำ)
print("{} {}".format(name, age)) # "John 35" - format()

7. Split และ Strip

# split() - แยก String เป็น List
"My name is John".split()           # ['My', 'name', 'is', 'John']
"John, Rose, Jack".split(", ")      # ['John', 'Rose', 'Jack']

# strip() - ลบ whitespace หน้า/หลัง
"  Hello World  ".strip()   # "Hello World"
"  Hello World  ".lstrip()  # "Hello World  "
"  Hello World  ".rstrip()  # "  Hello World"

# splitlines() - แยกบรรทัด
"Line1\nLine2\nLine3".splitlines()  # ['Line1', 'Line2', 'Line3']

8. String Formatting

f-strings (Python 3.6+ ✅ แนะนำ)

name = "John"
age = 30

f"Hello, {name}!"                    # "Hello, John!"
f"{name} is {age} years old"         # "John is 30 years old"
f"Next year: {age + 1}"              # "Next year: 31"
f"Price: {1234.567:.2f}"             # "Price: 1234.57"
f"Hex: {255:#x}"                     # "Hex: 0xff"

.format() Method

"Hello, {}".format("John")                    # "Hello, John"
"I have a {}, {}, {}".format("dog", "cat", "rabbit")
# "I have a dog, cat, rabbit"
"I have a {1}, {0}, {2}".format("dog", "cat", "rabbit")
# "I have a cat, dog, rabbit" (positional)
"{friend} & {enemy}".format(friend="John", enemy="Jack")
# "John & Jack" (keyword)

% Formatting (Legacy)

"Hello %s" % "John"
"Age: %d, Height: %.2f" % (25, 5.75)

9. Case Conversion

text = "Hello World"

text.lower()      # "hello world"
text.upper()      # "HELLO WORLD"
text.title()      # "Hello World"
text.capitalize() # "Hello world"
text.swapcase()   # "hELLO wORLD"

10. Method อื่นๆ ที่มีประโยชน์

Methodคำอธิบายตัวอย่าง
startswith/endswithเช็ค prefix/suffix"hello".startswith("he") → True
find/indexหาตำแหน่ง substring"hello".find("ll") → 2
replaceแทนที่ substring"hello".replace("l", "x") → "hexxo"
countนับจำนวน substring"hello".count("l") → 2
partitionแยก 3 ส่วน (before, sep, after)"a.b.c".partition(".") → ('a', '.', 'b.c')
isalpha/isdigit/isalnumเช็คประเภทตัวอักษร"abc".isalpha() → True
zfillPad zeros ด้านหน้า"42".zfill(5) → "00042"

บทความเกี่ยวข้อง