how can I do this?

Eric Yohanson eay at oclearnet.com
Mon Jul 15 20:23:01 EDT 2002


On Mon, 15 Jul 2002 18:28:06 -0500, John Hunter
<jdhunter at nitace.bsd.uchicago.edu> wrote:

>>>>>> "Eric" == Eric Yohanson <eay at oclearnet.com> writes:
>
>    Eric> I would like to know if it is possible in python 2.21 to
>    Eric> make a text entry widget that initially show nothing but
>    Eric> when the user type the first character displays a template
>    Eric> like "00#00:01+2" for the previous I have only enter the
>    Eric> numbers 1 & 2. the numbers would need to enter from right
>    Eric> and travel to the left as more are entered replacing the "0"
>    Eric> place holders.  How difficult would this be to do and what
>    Eric> should my approach be to this.  Any help wuld be great.
>
>Getting sinlge chars in python is platform and GUI dependent (search
>for getchar on groups.google.com in comp.lang.python for some
>suggestions).
>
>But assuming you can get the chars, here is some code that will do the
>template substitution.  I use a list of chars as input.  I found it
>easier to do this by first flipping the template string from left to
>right and using python's index function, which searches from the left.
>
>import string
>
>def fliplr(s):
>    "flip the string s from left to right"
>    out = ''
>    for i in range(len(s)-1, -1, -1):
>        out += s[i]
>    return out
>    
>def replchars(template, chars, token='0'):
>    "replace the kth instance of token in template with chars[k]"
>    out = map(None, template)  # out is a list of chars in template
>    for c in chars:
>        ind = out.index(token)
>        if ind==-1:
>            raise ValueError, 'Could not find token %s in template'
>        out[ind] = c
>
>    return string.join(out, "")
>
>template = "00#00:00+0"
>chars = ['1', '2', '3', '4', '5', '6', '7']
>
>rtemplate = fliplr(template)
>for i in range( len(chars) ):
>    rchars = fliplr( chars[0:i+1] )
>    print fliplr( replchars( rtemplate, rchars) )
>
>
>
>The output is:
>00#00:00+1
>00#00:01+2
>00#00:12+3
>00#01:23+4
>00#12:34+5
>01#23:45+6
>12#34:56+7
>
>
>Here's a shorter, but possibly more obscure version:
>
>import string
>
>def rsub(template, chars, token='0'):
>    out = map(None, template)
>    # get the indicies of the tokens in reverse order
>    inds = [ i for i in range(len(template)-1, -1, -1) if template[i]==token]
>    N = len(chars)
>    for i in range( len(chars) ):
>        out[inds[i]] = chars[N-i-1]
>    return string.join(out, "")
>
>template = "00#00:00+0"
>chars = ['1', '2', '3', '4', '5', '6', '7']
>
>for i in range( len(chars)) :
>    print rsub(template, chars[0:i+1])
>
>HTH,
>JDH


Thanks for the quick help.  I never thought about reversing the string
(I guess I was just looking at this thing to long) . This should work
just fine.  I search for the getchar info. Once again thanks

Eric




More information about the Python-list mailing list