Way to split a string in Python without using the .split function [duplicate]

送分小仙女□ 提交于 2020-12-16 07:51:05

问题


Here is my code:

words = firstsentence.split(' ')

firstsentence is a user input. The variable 'words' stores the word by word separated form of the user input.

For example, if firstsentence was "I like to do coding", .split would save it as a list of separated words in the variable words.

What I want to know is, is there any way to do exactly what .split does but without involving any built-in python functions like .split?

It has to separate the words and then store the separated words in a variable.


回答1:


words = []
current_word = ""
for char in firstsentence:
    if char == " ":
        words.append(current_word)
        current_word = ""
    else:
        current_word += char

words.append(current_word)

This iterates all the characters and if current character is normal character, it appends it to current_word. If, however, current character is space, it appends the word to words list and resets the temporary word.

Edit: I fixed the example by adding last line, thanks Tomerikoo.




回答2:


It’s really hard to know what counts as a built-in function in the OP, but here is one solution using slicing:

start = 0
words = []
for ix, x in enumerate(firstsentence):
    if x == ' ':
        words.append(firstsentence[start:ix])
        start = ix + 1
if start < len(firstsentence):
    words.append(firstsentence[start:])


来源:https://stackoverflow.com/questions/41526283/way-to-split-a-string-in-python-without-using-the-split-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!