Python String Methods ที่ใช้บ่อยๆ

Grassroot Engineer
5 min readFeb 8, 2020

--

String methods เป็นวิธีในการจัดการกับข้อมูลประเภทข้อความซึ่งบางครั้งลืมครับ ฉะนั้นอะไรที่ต้องใช้ลองมาดูกันเลยดีกว่า

strip, isdigit, join, replace, capitalize, title, upper, lower, split, startswith, removeprefix, removesuffix, isnumeric, zfill(<total digits>), rjust, ljust, center, count, index, find, isalnum, islower, isupper, partition,

สำหรับ Built-in functions ตัวอื่นๆ ติดตามได้ที่นี่ครับ => medium
สำหรับ lambda, filter, zip, reduce => medium
สำหรับ list mehods => medium
สำหรับ dict methods => medium

1. strip()

strip method เป็น method ที่เอาไว้ลบช่องว่างก่อนและหลังของ string นะคับ (ภาษาอื่นอาจเรียกว่า trim).

2. isdigit()

เป็นการเช็คว่า ชุด string ที่เราต้องการตรวจสอบ มีตัวเลขบ้างรึป่าว เช่น ตรวจสอบว่า ป้ายทะเบียน “1กท 4567” มีตัวเลขบ้างไหม ถ้ามีตัวเลขให้นำตัวเลขทั้งหมดมาบวกกัน

คัดเฉพาะตัวเลขนำมาบวกกัน

หรือสามารถนำมา apply ใช้ในการคัดเฉพาะตัวเลขของหน้าบัตรเครดิตก็ได้นะเช่น

คัดเฉพาะตัวเลขนำมา concat และแสดง

3. join()

การ join จะอนุญาตให้เรานำ string ที่อยู่ใน Tuple, List, Set มาเชื่อมเข้าด้วยกันได้ เช่น

การใช้งานแบบทั่วๆไป จัดเรียงรูปแบบของ สถานี MRT ใน tuple

ต่อไปจะเป็นการประยุกต์สร้าง program password_generator นะคับ

password generator by random lib.

4. replace()

ใช้สำหรับแทนที่ คือ ถ้าเจอ string ตัวนี้ ก็ให้แทนที่ด้วยตัวนี้ (และเรายังสามารถ raplace ได้มากกว่า 1 ตัวอักษรด้วยนะคับ) เช่น

เราสามารถ replace แค่ตัวอักษรเดียว หรือ หลายๆตัวอักษรก็ได้นะ

5. capitalize()

สำหรับ method นี้เป็นการทำให้ตัวอักษรตัวแรกของ sting เป็นตัวพิมพ์ใหญ่นะคับ (เฉพาะตัวแรกแค่ตัวเดียวในประโยคเท่านั้นนะคับ) เช่น

s = "atthana phiphat ROV"
print(s.capitalize())
#==============================================================
Atthana phiphat rov # นั่นคือ เฉพาะ "A" ตัวแรกของชุด string แค่ตัวเดียว

6. title()

สำหรบ method title จะคล้ายๆกับ อันบนนะคับ แต่ title จะแปลงเป็นตัวพิมพ์ใหญ่เฉพาะตัวหน้าของคำเท่านั้น (ตัวแรกของทุกๆคำในประโยค) เช่น

def demo_title():
s = "the land of smiles"
print(s.title())
demo_title()
#==============================================================
The Land Of Smiles # เฉพาะตัวแรกของคำเท่านั้นที่เป็นตัวพิมพ์ใหญ่ [Finished in 0.1s]

7. upper(), lower()

2 ตัวนี้ก็ตรงๆตัวเลยนะคับ คือ การทำให้ชุด String ทั้งหมดเป็นตัวพิมพ์เล็กหรือตัวพิมพ์ใหญ่ เช่น

s = "atthana phiphat ROV"
print(s.upper())
print(s.lower())
#=======================================================
ATTHANA PHIPHAT ROV # อันนี้คือ upper() จะเป็นตัวพิมพ์ใหญ่หมด
atthana phiphat rov # อันนี้คือ lower() จะเป็นตัวพิมพ์เล็กหมด

ส่วนวิธีการประยุกต์ใช้ในงานจริงนะคับ เช่น การตรวจสอบ input ที่รับค่าเข้ามาโดยเราสามารถทำการตรวจสอบแค่ค่าเดียว โดยทำการแปลงให้เป็นตัวพิมพ์ที่เราต้องการก่อนได้เช่น

def demo_upper():
choice = input("[M]ail, [F]emale : ")
if choice.upper() == "M":
print("male")
else:
print("female")
#===========================================================
ในเคสนี้คือ เป็นการรับค่า Input ว่าจะเป็น male หรือ female โดยการทำให้เป็นตัวพิมพ์ใหญ่ก่อน เพื่อที่ว่าจะได้เช็คแค่ "M" ตัวเดียวเท่านั้น
หรือเราอาจเขียนโดยการใช้ or ก็ได้นะคับเช่น
if choice == "M" or choice == "m": # อยู่ที่เราจะจะออกแบบ

8. split()

สำหรับ split เป็นการแยกนะคับตามตัวเลย ซึ่งถ้าเรากำหนดคำแยกใน argument มันก็จะแยกเมื่อเจอเครื่องหมายนั้น แต่ถ้าไม่กำหนดอะไรเลย มันจะแยกด้วย space นะคับ เช่น

def demo_split():
s = "the land of smiles"
a = s.split() # ไม่ได้กำหนดว่าแยกด้วยอะไร จึงแยกด้วย comma
print(a) # หลัง split แล้ว จะส่งค่ากลับมาเป็น list เข้าถึงแบบบรรทัดล่าง
print(a[1]) # เป็นการเข้าถึง คำว่า land นะ นับจาก 0 คือชุดแรก
demo_split()
#=========================================================
['the', 'land', 'of', 'smiles']
land

[Finished in 0.1s]

ตัวอย่างถัดไปนะคับ เป็นการลอง split ด้วย comma ดูบ้าง เช่น

def demo_split2():
t = "thailand, 5, 7, 3"
b = t.split(",") # เป็นการแบ่งด้วย comma
print(b) # บรรทัดนี้ แบ่งแล้วจะส่งค่าเป็น list กลับมา
x = "1920x1080"
p = x.split("x") # คราวนี้ลองแบ่งด้วยคำว่า "x" ดูบ้าง
print(p) # ได้รับค่าเป็น list เช่นกัน
w, h = x.split("x") # อัีกแบบนึง split เสดแล้ว ก็เก็บลงตัวแปรเลย
print(w, h)
demo_split2()
#===========================================================
['thailand', ' 5', ' 7', ' 3']
['1920', '1080']
1920 1080

[Finished in 0.1s]

อีกตัวอย่างนึงนะคับ เป็นการประยุกต์รับค่า ชื่อ นามสกุล และแบ่งอัตโนมัติด้วยช่องว่างนะคับ

def demo_split_app():
first_name, last_name = input("enter your full name: ").split()
print("first name:", first_name)
print("last name:", last_name)
demo_split_app()
#=============================================================
enter your full name: Atthana Phiphatthana # รับค่าเข้ามาทีเดียวเลย
first name: Atthana
last name: Phiphatthana # จะถูกแบ่งด้วย space โดยไม่สนใจความกว้างของ space
***Repl Closed***

9. startswith()

สำหรับ method นี้เป็นการเช็คว่า string ตัวนั้นมีคำที่ขึ้นต้นด้วยคำที่เรากำหนดไว้รึป่าว ไปดู used case กันเลยดีกว่าคับ

# startswith


faculties = ['Bachelor of Engineering', 'Science', 'Arts', 'Master of Business', 'bachelor of Law']
print(faculties)

new_names = []
for faculty in faculties:
prefix = 'bachelor of'
if faculty.lower().startswith(prefix):
faculty = faculty[len(prefix):].strip()
new_names.append(faculty)

print('\n')
print(new_names)
Apply “startswith” to check and cut string

10. removeprefix(), removesuffix()

สำหรับ 2 functions นี้จะมีให้ใช้ตั้งแต่ python vesion9 ขึ้นไปนะคับ จะยกตัวอย่างต่อเนื่องจากรูปข้างบนนะ ถ้าใช้อันนี้จะเขียนได้ง่ายกว่า

faculties = ['Bachelor of Engineering', 'Science', 'Arts', 'Master of Business', 'bachelor of Law']
print(faculties)

new_names = []
for faculty in faculties:
prefix = 'bachelor of'
if faculty.lower().startswith(prefix):
faculty = faculty.removeprefix(prefix).removesuffix('Engineering')
new_names.append(faculty)

print('\n')
print(new_names)
ตัวอย่างการใช้ removeprefix() และ removesuffix()

11. isnumeric()

สำหรับ method นี้จะใช้ในการเช็คว่า String ทั้งชุดนั้น เป็นตัวเลขรึป่าว

  • ต้องเป็นตัวเลขทั้งชุดนะ ถึงจะได้ True
  • ถ้าเป็นตัวอักษรทั้งหมดจะได้ False
  • ถ้าเป็นตัวเลข + ตัวอักษร ปนกัน ก็จะได้ False
word1 = '12345'
word2 = '12345ABCDE'
word3 = 'abcd'

print(word1.isnumeric()) # True
print(word2.isnumeric()) # False
print(word3.isnumeric()) # False

อ้าวแล้ว isnumeric() กับ isdigit() ต่างกันยังไงล่ะ

string1 = '12345'
string2 = '①②③④⑤'
string3 = 'ⅠⅡⅢ'
string4 = '12345.99'

print(string1.isnumeric()) # True
print(string2.isnumeric()) # True
print(string3.isnumeric()) # True
print(string4.isnumeric()) # False
print('---------------')
print(string1.isdigit()) # True
print(string2.isdigit()) # True
print(string3.isdigit()) # False
print(string4.isdigit()) # False
isnumeric() vs isdigit()

12. zfill(<total digits>)

  • การใช้ zfill() จะใช้กับ String ได้เท่านั้นนะ จึงต้องแปลง number ให้เป็น String ก่อน
  • Argument ที่ใส่ใน zfill() คือ จำนวน digits ทั้งหมดที่เราต้องการ
numbers = [1, 2, 3, 4, 5]

print([str(number).zfill(5) for number in numbers])


# output
# ['00001', '00002', '00003', '00004', '00005']

13. rjust(<width>, <fillchar>), ljust()

Return a right-justified string of length width.
จริงๆแล้วคือ การ adjust String ทั้งฝั่งซ้ายและฝั่งขวาได้นั่นเอง

  • rjust = ชิดขวา (ข้อมูลชิดขวานะ)
  • ljust = ข้อมูลชิดซ้าย
rjust vs ljust

14. center()

สำหรับ method นี้จะเป็นการจัด center ให้กับ string within a specified width by adding padding to the left and right of the string.

Argument แรกคือ width, ถัดไปคือ fillchar นะ
Applying center() na

15. partition()

สำหรับ Method นี้เป็นการ split String ให้เป็น 3 parts based on a specified separator

syntax:
string.partition(separator)

เช่น จากตัวอย่างด้านล่างเป็นการแบ่งให้เป็น 3 parts ด้วยคำว่า ‘o’ จึงเป็นการแบ่งคำว่า ‘love’ ออกมาเป็น ‘l’, ‘o’, ‘ve’ แบบในรูปด้านล่างคับ

>>> text = 'love'

>>> text.partition('o')
('l', 'o', 've')

>>> list(text.partition('o')) # แปลงจาก tuple ให้เป็น list นะ
['l', 'o', 've']

อีกตัวอย่างของการแบ่งตัวคำว่า ‘Python’

sentence = "I love Python programming"
words = sentence.partition("Python")
print(words)

# output
# ('I love ', 'Python', ' programming')

แต่ๆๆ ถ้าใน string มีตัว separator ที่มากกว่า 1 ตัว จะยึดแค่ตัวแรกตัวเดียวนะ เช่น คำว่า ‘love q mak mak’ จะเห็นว่ามี space ถึง 3 ตัว
แต่เมื่อใช้ partition(‘ ‘) จะแบ่งตัว space ตัวแรกตัวเดียวเท่านั้น ดังภาพด้านล่างเลยครับ

>>> text = 'love q mak mak'

>>> text.partition(' ')
('love', ' ', 'q mak mak')
https://www.linkedin.com/feed/update/urn:li:activity:7070409695013834753/?utm_source=share&utm_medium=member_android

ไว้พบกันใหม่ตอนถัดไปครับ
GRASSROOT ENGINEER

--

--