Jython 随机字符串生成
因此,我需要创建一个方法,根据 jython 中的给定长度返回随机字符串。如果我可以实现 python random ,那就很容易了,但是我找不到办法做到这一点,因为在每个随机示例中,我发现使用 java random 类而不是 python。 这是代码位:
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
我试图根据包含我需要的所有字符的字符串创建一个字符串。我只是无法找到一种通过索引访问字符串中的字符的方法,就像在 C# 中一样。
有什么想法可以做到这一点,甚至可以导入 python 随机类吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaDocs 提供指导。
JavaDocs guide the way.
试试这个,它适用于 Jython:
请注意,我使用的是 Jython 的
random
模块,而不是 Java 的Random
类。一个更短的版本,使用带有模块级导入的列表推导式(按照 pep-8):Try this, it works for me with Jython:
Notice that I'm using Jython's
random
module, not Java'sRandom
class. An even shorter version, using list comprehensions with module-level imports (as per pep-8):