ใน Python ออบเจ็กต์ str จัดการข้อมูลข้อความ สตริงเป็น immutable และเป็นลำดับของ Unicode characters สามารถกำหนดด้วย single quote, double quotes หรือ triple quotes
เมธอดสตริงสำคัญ
| เมธอด | คำอธิบาย |
|---|---|
capitalize() | ตัวอักษรแรกเป็นพิมพ์ใหญ่ |
center(width[, fillchar]) | จัดกึ่งกลาง เติมอักขระ (default space) |
count(sub[, start[, end]]) | นับจำนวน substring |
find(sub[, start[, end]]) | หาตำแหน่งแรกของ substring |
format(*args, **kwargs) | จัดรูปแบบสตริง |
isalnum() | ตรวจสอบ alphanumeric |
isalpha() | ตรวจสอบตัวอักษรทั้งหมด |
isdigit() | ตรวจสอบตัวเลขทั้งหมด |
isspace() | ตรวจสอบ whitespace |
join(iterable) | รวมสตริง |
ljust(width[, fillchar]) | จัดชิดซ้าย |
rjust(width[, fillchar]) | จัดชิดขวา |
lower() | แปลงเป็นพิมพ์เล็ก |
split(sep=None, maxsplit=-1) | แยกสตริงด้วย separator |
strip([chars]) | ตัดอักขระนำหน้า/ท้าย |
swapcase() | สลับพิมพ์ใหญ่/เล็ก |
upper() | แปลงเป็นพิมพ์ใหญ่ |
zfill(width) | เติมศูนย์นำหน้าให้ครบความกว้าง |
ตัวอย่างโค้ด
myStr1 = 'This is a Python String'
myStr2 = "hello world"
print(myStr2)
print(myStr2.capitalize())
print(myStr2.center(len(myStr1)))
print(myStr1)
print(myStr1.find('Py'))
myStr3 = 'abc123'
print(myStr3.isalnum())
print(myStr3.isdigit())
print('AB'.join('XY'))
print(myStr2.rjust(20, '_'))
print(myStr1.swapcase())
print('2509'.zfill(10))
ผลลัพธ์
hello world Hello world hello world This is a Python String 10 True False XABY __________hello world tHIS IS A pYTHON sTRING 0000002509