Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains only characters from a given set in python

I have a a user-inputted polynomial and I only want to use it if it only has characters in the string 1234567890^-+x.

How can I check if it does or not without using external packages? I only want to use built-in Python 2.5 functions.

I am writing a program that runs on any Mac without needing external packages.

like image 319
user2658538 Avatar asked Dec 22 '13 03:12

user2658538


2 Answers

Here are some odd ;-) ways to do it:

good = set('1234567890^-+x')

if set(input_string) <= good:
    # it's good
else:
    # it's bad

or

if input_string.strip('1234567890^-+x'):
    # it's bad!
else:
    # it's good
like image 70
Tim Peters Avatar answered Sep 20 '22 09:09

Tim Peters


Use a regular expression:

import re

if re.match('^[-0-9^+x]*$', text):
    # Valid input

The re module comes with Python 2.5, and is your fastest option.

Demo:

>>> re.match('^[-0-9^+x]*$', '1x2^4-2')
<_sre.SRE_Match object at 0x10f0b6780>
like image 34
Martijn Pieters Avatar answered Sep 22 '22 09:09

Martijn Pieters