简体   繁体   中英

Jython random string generation

So, I need to make a method that would return a random string based on given length in jython. It would be easy if I could implement python random, but on I could not find a way to do that, since in every random example I found that java random class is used instead of python. Here is the code bit:

  def getrstr (self, length):
    from java.util import Random
    import string
    chars = string.letter + string.digits
    str = ''
    for i in range(1, (length+1)):
      ind = random.nextInt(62) #there should be 62 charicters in chars string
      c = #this is the part where i should get radom char from string using ind
      str = str + c
    return str

I am trying to make a string based on string containing all chars I need. I just can't seam to find a way to access char in string by index, like I would in C#.

Any ideas how to do that or maybe even import python random class?

c = chars.charAt(ind);

JavaDocs指导方式。

Try this, it works for me with Jython:

def getrstr(self, length):
    import random, string
    seq = string.letters + string.digits
    randomstr = []
    for i in xrange(length):
        randomstr.append(random.choice(seq))
    return ''.join(randomstr)

Notice that I'm using Jython's random module, not Java's Random class. An even shorter version, using list comprehensions with module-level imports (as per pep-8):

import random, string

def getrstr(self, length):
    seq = string.letters + string.digits
    return ''.join(random.choice(seq) for _ in xrange(length))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM