การดำเนินการกับสตริง

Regular Expressions ใน Python

Maria Eugenia Inzaugarat

Data Scientist

ปรับตัวพิมพ์

my_string = "tHis Is a niCe StriNg"
  • แปลงเป็นตัวพิมพ์เล็ก
print(my_string.lower())
this is a nice string
  • แปลงเป็นตัวพิมพ์ใหญ่
print(my_string.upper())
THIS IS A NICE STRING
Regular Expressions ใน Python

 

my_string = "tHis Is a niCe StriNg"

 

  • แปลงอักขระแรกเป็นตัวพิมพ์ใหญ่
print(my_string.capitalize())
This is a nice string
Regular Expressions ใน Python

การแบ่งสตริง

my_string = "This string will be split"
  • แบ่งสตริงเป็นลิสต์ของสตริงย่อย
my_string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
my_string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
Regular Expressions ใน Python

 

my_string = "This string will be split\nin two"

print(my_string)
This string will be split
in two

Regular Expressions ใน Python
  • แบ่งที่ขอบบรรทัด
my_string = "This string will be split\nin two"

 

my_string.splitlines()
['This string will be split', 'in two']
Regular Expressions ใน Python

การเชื่อมสตริง

  • เชื่อมสตริงจากลิสต์หรือ iterable อื่น

 

my_list = ["this", "would", "be", "a", "string"]
print(" ".join(my_list))
this would be a string
Regular Expressions ใน Python

การตัดอักขระ

  • ตัดอักขระจากซ้ายไปขวา: .strip()

 

my_string = " This string will be stripped\n"
my_string.strip()
'This string will be stripped'
Regular Expressions ใน Python

 

my_string = " This string will be stripped\n"
  • ตัดอักขระออกจากด้านขวา
my_string.rstrip()
' This string will be stripped'
  • ตัดอักขระออกจากด้านซ้าย
my_string.lstrip()
'This string will be stripped\n'
Regular Expressions ใน Python

มาฝึกกันเถอะ!

Regular Expressions ใน Python

Preparing Video For Download...