Reputation: 43
first of all, sorry for my bad english. I'm a beginner programmer and I have some problems with my python program. I have to make a program that normalizes the whitespaces and the punctuation, for example:
If I put a string called
" hello how, are u? "
The new string has to be...
"Hello how are u"
But in my code, the result appears like this and I dont know why:
"helloo how,, aree u??"
Note: I can't use any kind of function like split(), strip(), etc...
Here is my code:
from string import punctuation
print("Introduce your string: ")
string = input() + " "
word = ""
new_word = ""
final_string = ""
#This is the main code for the program
for i in range(0, len(string)):
if (string[i] != " " and (string[i+1] != " " or string[i+1] != punctuation)):
word += string[i]
if (string[i] != " " and (string[i+1] == " " or string[i+1] == punctuation)):
word += string[i] + " "
new_word += word
word = ""
#This destroys the last whitespace
for j in range(0,len(new_word)-1):
final_string += new_word[j]
print(final_string)
Thank you all.
EDIT:
Now i have this code:
letter = False
for element in my_string:
if (element != " " and element != punctuation):
letter= True
word += element
print(word)
But now, the problem is that my program doesn't recognize the punctuation so if i put:
"Hello ... how are u?"
It has to be like "Hellohowareu"
But it is like:
"Hello...howareu?
Upvotes: 0
Views: 1398
Reputation: 11781
Now this looks a lot like homework, so here's my stream processing solution, if you can explain this to your teacher, I doubt they'd mind you didn't really do it yourself 😼
def filter(inp):
for i in inp:
yield " " if i in " ,.?!;:" else i
def expand(inp):
for i in inp:
yield None if i == " " else object(), i
def uniq(inp):
last = object()
for key, i in inp:
if key == last:
continue
yield key, i
def compact(inp):
for key, i in inp:
yield i
normalised = compact(uniq(expand(filter(input()))))
Upvotes: 0
Reputation: 1533
Ok, so first off, you don't need to loop over a range, strings in python are iterable. For example:
my_string = 'How are you?'
for char in my_string:
#do something each character
Secondly, you're using a very spotty methodology for what you want to remove. It seems your method for catching spaces that occur after a character causes a double append of the last character. I would use a different method much more heavily centered on where you are, not what's in front of you.
Upvotes: 0
Reputation: 599620
I'm not going to write the code for you since this is obviously homework, but I will give you some hints.
I think your approach of checking the next character is a bit error-prone. Rather, I would have a flag that you set when you see a space or punctuation. The next time through the loop, check if the flag is set: if it is, and you still see a space, then ignore it, otherwise, reset the flag to false.
Upvotes: 3