0

I am trying to verify the my string only contains the following values, '\n, '.', and 'o'. They do not all need to be there, but if anything outside of those characters is included my function should return false.

I have one string that does include these characters, but it also includes '0'. With my function though, this returns to true.


I am primarily having issues with the first line, all others work as expected. I am not able to use regex so an alternative would be greatly appreciated!
1
  • This may not refere to the question, but this is a bad practice to use structures like if (len(s)==10 or len(s)== 14) and s[2]=='\\': return True. Your statement under if ((len(s)==10 or len(s)== 14) and s[2]=='\\') returns bool itself. It will be more correct to write like return (len(s)==10 or len(s)== 14) and s[2]=='\\' Commented Oct 17, 2019 at 19:08

4 Answers 4

3

Use the all function:

if all (char in ".o\n" for char in s):

If you prefer, make a list of chars instead of a string:

if all (char in ['.', 'o', '\n'] for char in s):
Sign up to request clarification or add additional context in comments.

Comments

1

You could use sets for this:

if s and set(s) - set('\n.o'):
  return False
# s consists entirely of \n, o and .

It's not clear to me what should happen if s is empty. The above code would allow it; if you wish to reject it, change the first line to

if set(s) - set('\n.o'):

1 Comment

You could remove the conditional and just do not set(s) - set('\n.o')
0

Here's another way you could do it:

allowed_chars = ['\n', '.', 'o']
your_string = '\n.o'

all([False for i in set(your_string) if i not in allowed_chars])

Returns True.

And your_string = '\n.ogg' returns False.

Comments

0

Is this what you're after?

tests = [
  r'ab\cdefgho',
  r'ab\cdefgh.',
  r'ab\cdegh\n',
  r'ab\cdc.o\n'
]

def check_string(s):
  if ('\\n' in s) or ('.' in s) or ('o' in s):
    if (len(s)==10 or len(s)== 14) and s[2]=='\\':
      return True
    else:
      return False
  else:
    return False

for t in tests:
  assert check_string(t)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.