0
ans = input("Enter a sentence: ")

count = ans.count(" ") + 1

final = ""

for i in range(count):

    space = ans.find(" ")
    word = ans[0:space]

    final += word + ","

    ans = ans.replace(word,"")

print(final)

The code above shows my attempt to separate words in a sentence with a ",". After the first loop the variable "word" is empty and does not take on the next part of the sentence. Please help

  • 1
    Duplicate? [Split a String by a Delimiter in Python](https://stackoverflow.com/questions/3475251/split-a-string-by-a-delimiter-in-python) – 12944qwerty Apr 30 '21 at 15:39
  • Does this answer your question? [Split a string by a delimiter in python](https://stackoverflow.com/questions/3475251/split-a-string-by-a-delimiter-in-python) – Robert Apr 30 '21 at 15:59

1 Answers1

0

There are several routes for this, perhaps the simplest and most robust is to .split() and join the strings

this will create a list separated by any whitespace chars and then rebuild a new string with them joined by commas

>>> mystring = "some string with spaces"
>>> ",".join(mystring.split())
'some,string,with,spaces'

You might consider a regex if you need something more robust (like handling a terminating .), and may consider doing both (split, regex, join) for a full solution

ti7
  • 16,375
  • 6
  • 40
  • 68