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

Python String Methods: คู่มือเมธอดสตริงครบถ้วน พร้อมตัวอย่าง

Python มอบเมธอดสตริงที่เป็น built-in (สร้างตัว) ให้ใช้งานมากมาย นี่คือรายการเมธอดสตริงที่มีใน Python 3 พร้อมคำอธิบายและตัวอย่างโค้ด

เมธอด คำอธิบาย ตัวอย่าง
capitalize() คืนค่าสตริงที่ตัวอักษรแรกเป็นพิมพ์ใหญ่ และตัวอื่นเป็นพิมพ์เล็ก
>> mystring = "hello python"
>>> print(mystring.capitalize())
Hello python
casefold() คืนค่าสตริงที่แปลงเป็น casefolded (เหมาะสำหรับการเปรียบเทียบไม่สนใจพิมพ์ใหญ่/เล็ก)
>> mystring = "hello PYTHON"
>>> print(mystring.casefold())
hello python
center(width, [fillchar]) จัดตำแหน่งสตริงให้อยู่กึ่งกลางในความกว้าง width โดยเติม fillchar (ค่าเริ่มต้นคือ space)
>> mystring = "Hello"
>>> x = mystring.center(12, "-")
>>> print(x)
---Hello----
count(sub, [start], [end]) นับจำนวนครั้งที่ substring sub ปรากฏ (ไม่ทับซ้อน) ในช่วง [start, end]
>> mystr = "Hello Python"
>>> print(mystr.count("o"))  # 2
>>> print(mystr.count("th")) # 1
encode(encoding="utf-8", errors="strict") คืนค่า bytes object ที่เข้ารหัสจากสตริง encoding เริ่มต้นคือ utf-8
>> mystr = 'python!'
>>> print(mystr.encode("ascii", "ignore"))
b'python!'
endswith(suffix, [start], [end]) คืนค่า True หากสตริงลงท้ายด้วย suffix ที่ระบุ
>> mystr = "Python"
>>> print(mystr.endswith("hon"))  # True
expandtabs(tabsize=8) แทนที่ tab character ด้วย space ตามขนาด tab ที่กำหนด
>> mystr = "1\t2\t3"
>>> print(mystr.expandtabs(4))
1   2   3
find(sub, [start], [end]) คืนดัชนีต่ำสุดที่พบ sub ใน slice s[start:end] คืน -1 หากไม่พบ
>> mystring = "Python"
>>> print(mystring.find("on"))  # 4
format(*args, **kwargs) จัดรูปแบบสตริงด้วย replacement fields ใน {}
>> print("{} and {}".format("Apple", "Banana"))
Apple and Banana
format_map(mapping) คล้าย format(**mapping) แต่ใช้ mapping โดยตรง ไม่คัดลอกเป็น dict
>> lunch = {"Food": "Pizza", "Drink": "Wine"}
>>> print("Lunch: {Food}, {Drink}".format_map(lunch))
Lunch: Pizza, Wine
index(sub, [start], [end]) ค้นหา sub และคืนตำแหน่งที่พบ โยน ValueError หากไม่พบ
>> mystr = "HelloPython"
>>> print(mystr.index("P"))  # 5
isalnum() True หากทุกตัวอักษรเป็น alphanumeric (อักษรหรือตัวเลข)
>> "HelloPython".isalnum()  # True
>>> "$*%!!!".isalnum()       # False
isalpha() True หากทุกตัวอักษรเป็นอักษรภาษาอังกฤษ
>> "HelloPython".isalpha()  # True
>>> "123".isalpha()          # False
isdecimal() True หากทุกตัวอักษรเป็นเลขทศนิยม (0-9 และอักขระ Unicode decimal)
>> "133".isdecimal()  # True
>>> "1.23".isdecimal() # False
isdigit() True หากทุกตัวอักษรเป็นตัวเลข (รวม superscript digits)
>> "133".isdigit()  # True
>>> "\u00B2".isdigit() # True (²)
isidentifier() True หากสตริงเป็น identifier ที่ถูกต้องของ Python
>> "_user_123".isidentifier()  # True
>>> "133".isidentifier()       # False
islower() True หากตัวอักษรทั้งหมดเป็นพิมพ์เล็ก (และมีอย่างน้อย 1 ตัวอักษร)
>> "python".islower()  # True
>>> "Python".islower()  # False
isnumeric() True หากทุกตัวอักษรเป็นตัวเลข (รวมเศษส่วน Unicode, roman numerals)
>> "133".isnumeric()  # True
>>> "½".isnumeric()    # True
isprintable() True หากทุกตัวอักษรพิมพ์ได้ (ไม่รวม control characters)
>> "Hello".isprintable()  # True
>>> "\t".isprintable()     # False
isspace() True หากทุกตัวอักษรเป็น whitespace (space, tab, newline)
>> "   ".isspace()  # True
>>> "Hello".isspace() # False
istitle() True หากสตริงเป็น title case (ตัวแรกของแต่ละคำเป็นพิมพ์ใหญ่)
>> "Hello World".istitle()  # True
>>> "Hello world".istitle()  # False
isupper() True หากตัวอักษรทั้งหมดเป็นพิมพ์ใหญ่ (และมีอย่างน้อย 1 ตัวอักษร)
>> "PYTHON".isupper()  # True
>>> "Python".isupper()  # False
join(iterable) รวมสมาชิกของ iterable ด้วยสตริงนี้เป็น separator
>> "-".join("123")  # "1-2-3"
ljust(width[, fillchar]) จัดชิดซ้ายในความกว้าง width เติม fillchar
>> "Hello".ljust(10, "_")  # "Hello_____"
lower() แปลงสตริงเป็นพิมพ์เล็กทั้งหมด
>> "Python".lower()  # "python"
lstrip([chars]) ลบ whitespace (หรือ chars ที่ระบุ) ด้านซ้าย
>> " Hello ".lstrip()  # "Hello "
maketrans(x[, y[, z]]) คืน translation table สำหรับ translate()
>> trans = str.maketrans("abc", "123")
>>> "abc".translate(trans)  # "123"
partition(sep) แบ่งสตริงเป็น tuple 3 ส่วน: (ก่อน sep, sep, หลัง sep)
>> "Hello-Python".partition("-")  # ('Hello', '-', 'Python')
replace(old, new[, count]) แทนที่ old ด้วย new จำนวน count ครั้ง
>> "Hello Hello".replace("Hello", "Hi", 1)  # "Hi Hello"
rfind(sub[, start[, end]]) ค้นหา sub จากขวาไปซ้าย คืนตำแหน่งสุดท้ายที่พบ
>> "Hello-Python".rfind("o")  # 9
rindex(sub[, start[, end]]) เหมือน rfind แต่โยน ValueError หากไม่พบ
>> "Hello".rindex("l")  # 3
rjust(width[, fillchar]) จัดชิดขวาในความกว้าง width
>> "Hello".rjust(10, "-")  # "-----Hello"
rpartition(sep) เหมือน partition แต่ค้นหา sep จากขวาไปซ้าย
>> "Hello Python".rpartition(" ")  # ('Hello', ' ', 'Python')
rsplit(sep=None, maxsplit=-1) แบ่งสตริงจากขวาไปซ้าย คืน list
>> "a-b-c".rsplit("-", 1)  # ['a-b', 'c']
rstrip([chars]) ลบ whitespace (หรือ chars) ด้านขวา
>> "Hello ".rstrip()  # "Hello"
split(sep=None, maxsplit=-1) แบ่งสตริงเป็น list ตาม separator
>> "Hello,Python".split(",")  # ['Hello', 'Python']
splitlines([keepends]) แบ่งสตริงที่ line breaks คืน list
>> "a\nb\r\nc".splitlines()  # ['a', 'b', 'c']
startswith(prefix[, start[, end]]) True หากสตริงขึ้นต้นด้วย prefix
>> "Hello".startswith("He")  # True
strip([chars]) ลบ whitespace (หรือ chars) ทั้งสองข้าง
>> " Hello ".strip()  # "Hello"
swapcase() สลับพิมพ์ใหญ่/เล็ก
>> "Hello".swapcase()  # "hELLO"
title() แปลงตัวแรกของแต่ละคำเป็นพิมพ์ใหญ่
>> "hello world".title()  # "Hello World"
translate(table) แปลงสตริงตาม translation table
>> trans = str.maketrans("aeiou", "12345")
>>> "hello".translate(trans)  # "h2ll4"
upper() แปลงสตริงเป็นพิมพ์ใหญ่ทั้งหมด
>> "hello".upper()  # "HELLO"
zfill(width) เติมศูนย์ด้านซ้ายจนครบ width ตัว
>> "42".zfill(5)  # "00042"
>>> "-42".zfill(5) # "-0042"