【发布时间】:2015-08-29 00:05:18
【问题描述】:
我正在尝试制作一个随机字符串生成器,它可以生成长度为 min
我的输入:a ä æ e i ï o u ü b ḅ d ḍ f v h ḥ k g l ľ m y n ṇ p ṕ r ṛ s j w ẉ x x̣ 5 10
from random import *
#Class random generator
#@variables list aList,boolean again, int maximum, int minimum
class randomStringGenerator:
def __init__(this):
aList = []
allowed = input("What are the characters that you will allow?\n" +
"Please press the chracters you want and leave a space between each character\n, then enter to submit\n" +
"e.g. 'a' 'b' 'c'\n ")
aList = allowed.split(" ")
minimum = input("What is the minimum number of characters in the string that you want? \n")
maximum = input("What is the maximum number of characters in the string that you want? \n")
this.aList = aList
this.minimum = int(minimum)
this.maximum = int(maximum)
again = True
this.again = again
#generateRandNum generates a random int from a minimum to b maximum
#@param this,mini,maxi
#@return int x the integer that was chosen
def generateRandNum(this,mini,maxi):
x = randint(mini,maxi)
return x
#generateRandString generates the actual string randomly
def generateRandString(this):
ans = ""
strSize = this.generateRandNum(this.minimum,this.maximum)
pos = 0
while(pos < strSize):
size = len(this.aList)
idx = this.generateRandNum(0,size - 1)
char = this.aList[idx]
ans = ans + char
pos += 1
ans.encode('utf-8')
print(ans)
def getAgain(this):
return this.again
def replay(this):
x = input("Would you like to generate another string using the same settings? y/n \n")
if(x == "y"):
this.generateRandString()
else:
y = input("Would you like to generate another string using different settings? y/n \n")
if(y == "y"):
new = input("What are the new characters that you will allow? ")
mini = input("What is the new minimum number of characters? ")
maxi = input("What is the new maximum number of characters? ")
this.aList = new.split(" ")
this.minimum = int(mini)
this.maximum = int(maxi)
this.generateRandString()
else:
this.again = False
s = randomStringGenerator()
s.generateRandString()
while(s.getAgain()):
s.replay()
示例输出:如您所见,我将最少字符设置为 5 个,但只显示 2 个,并且由于某种原因多次打印...
What are the characters that you will allow?
Please press the chracters you want and leave a space between each character
, then enter to submit
e.g. 'a' 'b' 'c'
a ä æ e i ï o u ü b ḅ d ḍ f v h ḥ k g l ľ m y n ṇ p ṕ r ṛ s j w ẉ x x̣
What is the minimum number of characters in the string that you want?
5
What is the maximum number of characters in the string that you want?
10
o
oḅ
oḅ
oḅ
oḅ
oḅ
oḅ
【问题讨论】:
-
是 Python2.7 还是 Python3.x? unicode 是 Python3.x 的默认编码系统,因此编码不太可能成为问题。对于Python2.7,在开头添加
from __future__ import unicode_literals。如果脚本中有非 unicode 字符,请将# -*- coding: utf-8 -*-添加到代码的最顶部。 -
Python 3,但由于某种原因,除非我使用 .encode 方法,否则它无法正确显示在我的代码中
-
没关系,你是对的。字数没有达到限制的问题仍然是个问题。
-
你的意图是什么?对我来说,
generateRandString中的代码只是获取一个从 5 到 10 的随机数,然后生成一个该长度的字符串,您的代码似乎做得对。