文字列操作

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
Pythonで学ぶ正規表現

 

my_string = "tHis Is a niCe StriNg"

 

  • 先頭文字を大文字化
print(my_string.capitalize())
This is a nice string
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']
Pythonで学ぶ正規表現

 

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

print(my_string)
This string will be split
in two

Pythonで学ぶ正規表現
  • 行区切りで分割
my_string = "This string will be split\nin two"

 

my_string.splitlines()
['This string will be split', 'in two']
Pythonで学ぶ正規表現

結合

  • リストなどのイテラブルの文字列を連結

 

my_list = ["this", "would", "be", "a", "string"]
print(" ".join(my_list))
this would be a string
Pythonで学ぶ正規表現

文字の削除

  • 先頭と末尾の文字を削除: .strip()

 

my_string = " This string will be stripped\n"
my_string.strip()
'This string will be stripped'
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'
Pythonで学ぶ正規表現

Ayo berlatih!

Pythonで学ぶ正規表現

Preparing Video For Download...