0

I want to remove commas from one sentence and separate all the other words(a-z) and print them one by one.

a = input()
b=list(a)                      //to remove punctuations
for item in list(b):           //to prevent "index out of range" error. 
    for j in range(len(l)):
        if(item==','):
            b.remove(item)
            break
c="".join(b)                  //sentence without commas
c=c.split()
print(c)

My input is :

The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi.

and when I remove the comma:

... founded as a standard academyand developed to a university...

and when I split the words:

The
university
.
.
.
academyand
.
.
.

what can I do to prevent this? I already tried replace method and it doesn't work.

4 Answers4

2

You could replace , with a space assuming there is no space between , and next word in your input 1 and then perform split:

s = 'The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi.'

print(s.replace(',', ' ').split())
# ['The', 'university', 'was', 'founded', 'as', 'a', 'standard', 'academy', 'and', 'developed', 'to', 'a', 'university', 'of', 'technology', 'by', 'Habib', 'Nafisi.']

Alternatively, you could also try your hand at regex:

import re

s = 'The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi.'

print(re.split(r' |,', s))

1Note: This works even if you had space (multiple) after , because ultimately you split on whitespace.

Austin
  • 25,759
  • 4
  • 25
  • 48
1

Your issue seems to be that there is no space between the comma and the next word here: academy,and You could solve this by ensuring that there is a space so when you use b=list(a) that function will actually separate each word into a different element of the list.

Victor
  • 48
  • 1
  • 4
1

This is probably what you want, I see you forgot to replace comma with space.

stri = """ The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi."""
stri.replace(",", " ")
print(stri.split())

Will give you the output in a list:

['The', 'university', 'was', 'founded', 'as', 'a', 'standard', 'academy,and', 'developed', 'to', 'a', 'university', 'of', 'technology', 'by', 'Habib', 'Nafisi.']
user2906838
  • 1,178
  • 9
  • 20
1

If you consider words to be a series of characters that are separated by spaces, if you replace a , with nothing, then there will be no space between them, and it will consider it one word.

The easiest way to do this is to replace the comma with a space, and then split based on spaces:

my_string = "The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi."
list_of_words = my_string.replace(",", " ").split()
Kusti8
  • 81
  • 7