2

I have script like:

from string import digits, uppercase, lowercase, punctuation
from itertools import product

chars = lowercase + uppercase + digits + punctuation

for n in range(1,  2+1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

it works fine. Imagine chars is giving by an external user so:

import sys
from string import digits, uppercase, lowercase, punctuation
from itertools import product

chars = sys.argv[1] # sys.argv[1] is 'lowercase+uppercase+digits+punctuation'

for n in range(1,  2+1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

when run script.py: It has not the result when you say:

chars = lowercase + uppercase + digits + punctuation

Now how can I get the previous result?

4
  • When you say chars = 'lowercase+uppercase+digits+punctuation' the program doen't work. because lowercase and etc are functions not string... how can the the python these are not string and thy are functions Commented Feb 14, 2016 at 12:48
  • Let me update the question Commented Feb 14, 2016 at 12:48
  • Well, yes... because they're strings. If you want the attributes of string with those names, you must tell Python as much. Trivial research will tell you how. Commented Feb 14, 2016 at 12:49
  • 1
    A hint: string.lowercase == getattr(string, 'lowercase') assuming that you have imported string Commented Feb 14, 2016 at 12:51

1 Answer 1

3

You can use a dictionary mapping the user input to the corresponding strings.

>>> input_to_chars = {
...     'lowercase': lowercase,
...     'uppercase': uppercase,
...     'digits': digits,
...     'punctuation': punctuation
... }

Construct chars from the user input like this:

>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(input_to_chars[i] for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

Or with the hint from @schwobaseggl in the comments:

>>> import string
>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(getattr(string, i) for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

The dictionary solution is easy to extend, the getattr solution is good if you don't want to extend your program to accept user inputs which are not attributes of string.

Sign up to request clarification or add additional context in comments.

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.