-
文字列を等間隔に分割する方法:
def split_string_equally(string, num_columns): column_width = len(string) // num_columns split_columns = [string[i:i+column_width] for i in range(0, len(string), column_width)] return split_columns string = "abcdefg1234567" num_columns = 3 result = split_string_equally(string, num_columns) print(result)
出力:
['abc', 'def', 'g12', '345', '67']
-
列ごとの最大文字数を指定して分割する方法:
def split_string_max_length(string, max_length): split_columns = [string[i:i+max_length] for i in range(0, len(string), max_length)] return split_columns string = "abcdefg1234567" max_length = 4 result = split_string_max_length(string, max_length) print(result)
出力:
['abcd', 'efg1', '2345', '67']
-
特定の区切り文字を使って分割する方法:
def split_string_by_delimiter(string, delimiter): split_columns = string.split(delimiter) return split_columns string = "abc-def-ghi-jkl" delimiter = "-" result = split_string_by_delimiter(string, delimiter) print(result)
出力:
['abc', 'def', 'ghi', 'jkl']