' How are you? ' or 'How are you? 'Problem:
The problem is that when I send this to the file to search for the match response. It comes up without a match because the string is saved as:
'How are you?'
As you can see this has no spaces before or after. The single quotation marks. So when I run the search with it comes up with nothing and I don't really want to add unessessary lists with spaces just in case the program receives sloppy input.Solution:
It turns our that the solution is quite simple. Python provides two simple tools to remove extra white space before and after the sentence or even duplicate spaces between words in a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
###Removing Unwanted Whitespace In A String### | |
Comment_1 = " How are you? " | |
Comment_2 = " How are you? " | |
def remove_whitespace_either_side(comment): | |
comment = comment.strip() | |
print(comment) | |
def remove_any_duplicated_white_space(comment): | |
comment = " ".join(comment.split()) | |
print (comment) | |
print("The first comment has no extra spaces between words") | |
remove_whitespace_either_side(Comment_1) | |
remove_any_duplicated_white_space(Comment_1) | |
print("") | |
print("The second comment has extra spaces between words") | |
remove_whitespace_either_side(Comment_2) | |
remove_any_duplicated_white_space(Comment_2) | |
""" | |
RESULT | |
>>> | |
The first comment has no extra spaces between words | |
How are you? | |
How are you? | |
The second comment has extra spaces between words | |
How are you? | |
How are you? | |
>>> | |
""" |
But what happens if your program user is a bit of a typing numpty and manages to put extra white spaces between the works? For example:
' I am a typing numpty!'As you can see, the first function cannot deal with this.
This is where the second function, remove_any_duplicated_white_space , is so useful. This function uses two methods forming " ".join(variable.spit()). Here, we split all the words into individual strings and then join them back together into one string with a single space between each.
You can see the result of each in the code above.
Looking at the quality of input I have been getting for my chatbot I think I will be using the second function.
No comments:
Post a Comment