可以使用循环遍历字符串的每个字符,根据特定的分隔符来分割字符串。具体方法如下:
def split_string(string, delimiter):
result = []
start_idx = 0
for i in range(len(string)):
if string[i] == delimiter:
result.append(string[start_idx:i])
start_idx = i + 1
result.append(string[start_idx:])
return result
以上代码中,我们使用循环遍历字符串中的每个字符,如果遇到分隔符,就将分隔符前的字符串添加到结果列表中。最后在循环结束后,将最后一个分隔符后的字符串也添加到结果列表中。
下面是一个使用示例:
s = "hello,world"
delimiter = ","
result = split_string(s, delimiter)
print(result) # ['hello', 'world']
在上面的示例中,我们将字符串"hello,world"
以逗号为分隔符进行了分割,返回的结果为['hello', 'world']
。