Python String split ()เมธอด
ตัวอย่าง
แยกสตริงออกเป็นรายการที่แต่ละคำเป็นรายการ:
txt = "welcome to the jungle"
x = txt.split()
print(x)
ความหมายและการใช้งาน
วิธี การsplit()
แยกสตริงออกเป็นรายการ
คุณสามารถระบุตัวคั่น ตัวคั่นเริ่มต้นคือช่องว่างใดๆ
หมายเหตุ:เมื่อระบุ maxsplit รายการจะมีจำนวนองค์ประกอบที่ระบุบวกหนึ่ง
ไวยากรณ์
string.split(separator, maxsplit)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences" |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
แยกสตริงโดยใช้เครื่องหมายจุลภาค ตามด้วยช่องว่าง เป็นตัวคั่น:
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)
ตัวอย่าง
ใช้อักขระแฮชเป็นตัวคั่น:
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
ตัวอย่าง
แยกสตริงออกเป็นรายการที่มีสูงสุด 2 รายการ:
txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter
to 1, will return a list with 2 elements!
x = txt.split("#", 1)
print(x)