Wuchun
Wuchun

Reputation: 13

How to define a function that would check if a string have whitespaces after the sentence is finished?

Here's what I've tried so far

def whitespace(string):
    for s in string:
        if s[-1] :
        return ("'%s' ended with whitespace." % s)
    else:
       return ("'%s' was whitespace-free." % s)

Upvotes: 1

Views: 316

Answers (2)

Rui Botelho
Rui Botelho

Reputation: 751

You can use regular expressions(regex) for this situation:

def whitespace(string):
    import re
    if re.searh("\s+$",string)
        return ("'%s' ended with whitespace." % s)
    else:
       return ("'%s' was whitespace-free." % s)
  • "\s" means find one space
  • "\s+" means find one or more spaces
  • "\s+$" means find one or more spaces before JUST before the end of the string

Those strings are called regex (regular expression). Python, like many other languages, use those to find strings inside strings. The kind of regex that python uses comes from Perl.

Upvotes: 1

Alberto Coletta
Alberto Coletta

Reputation: 1593

How about this?

def whitespace(string):

    if string[-1] == " ":
        return True

    return False

You don't need to loop over the string, just access the last element.

This method returns a boolean, modify it whatever you want.

Upvotes: 1

Related Questions