问题
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