0

I was trying to create a function that only accepts a string with letters and only with one space between words, i was trying to define it without using regex, do you know how i can do it?

def corrigir_doc(doc):
    allow = {''}
    if allow not in doc or doc.isalpha() is False:
        raise ValueError('corrigir_doc: argumento invalido')

  • 1
    Why not use regex? it was specifically created for this kind of task – Einliterflasche Oct 29 '21 at 18:07
  • `''` is not a space. `' '` is. Also, why are you using brackets? That makes it a `set`. And don't use `is False`. Use `== False`. Or `not`. – 001 Oct 29 '21 at 18:08

1 Answers1

0

You can use str.isalpha and str.isspace for each of the character in the string, and also make sure the count of space is less than 2, and also check if the word doesn't end with space using str.endswith , if the condition is True, the normal flow for the function, else raise the desired error.

def func(doc):
    if all(c.isalpha() or c.isspace() for c in doc) \
            and doc.count(' ') < 2\
            and not doc.endswith(' '):
        # execute the function
        pass
    else:
        raise ValueError('Invalid data')
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • I tried to put a input like 'BuAaXOoxiIKoOkggyrFfhHXxR duJjUTtaCcmMtaAGga eEMmtxXOjUuJQqQHhqoada JlLjbaoOsuUeYy cChgGvValLCwMmWBbclLsNn LyYlMmwmMrRrongTtoOkyYcCK daRfFKkLlhHrtZKqQkkvVKza' but it didn't work, do you know the problem? –  Oct 29 '21 at 18:32
  • Looks like there is some confusion over "only with one space between words." This code only allows one or zero spaces in the entire string. – 001 Oct 29 '21 at 18:39
  • @JohnnyMopp Oh ok, I meant that the words were supposed to be separated with a only space. Do you know how i can do it? –  Oct 29 '21 at 18:56
  • For this code you can change `and doc.count(' ') < 2` to `and doc.count(' ') == 0` Note that there are 2 spaces there. – 001 Oct 29 '21 at 19:04