不使用内置的拆分函数按新行拆分字符串

2024-04-27 00:10:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建自己的函数,用\n(新行)分割字符串。我不想使用任何内置函数。如何做到这一点?你知道吗


Tags: 函数字符串内置
1条回答
网友
1楼 · 发布于 2024-04-27 00:10:42

试试这个:

def split_string(string, delimiter):
    output = []
    while delimiter in string:
        index = string.index(delimiter)

        output.append(string[0:index])
        string = string[index+1:]


    output.append(string)
    return output


str = """This is 
a string
of words
delimited
by slash n
ok"""
split_string(str, "\n")

操作:

['This is ', 'a string', 'of words', 'delimited', 'by slash n', 'ok']

相关问题 更多 >