Pythonのsplitの使い方

Pythonでは、「split()」関数は文字列を分割するために利用されます。この関数は、指定した区切り文字に基づいて文字列を複数のサブ文字列に分割し、それらのサブ文字列を含むリストを返します。以下は、「split()」関数を使用する基本的な構文です。

string.split(separator, maxsplit)

separatorパラメータは区切り文字で、文字または文字列を指定できます。既定値のNoneはスペースを表し、maxsplitパラメータはオプションで分割回数の最大値を指定します。

以下に例をいくつか示します。

# 使用空格分割字符串
string = "Hello World"
result = string.split()
print(result)  # 输出: ['Hello', 'World']

# 使用逗号分割字符串
string = "apple,banana,orange"
result = string.split(",")
print(result)  # 输出: ['apple', 'banana', 'orange']

# 使用换行符分割字符串
string = "apple\nbanana\norange"
result = string.split("\n")
print(result)  # 输出: ['apple', 'banana', 'orange']

# 指定最大分割次数
string = "apple,banana,orange"
result = string.split(",", 1)
print(result)  # 输出: ['apple', 'banana,orange']

注意、split()メソッドはリストを返して、それぞれの文字列をインデックスでアクセスできます。

bannerAds