[英]generate a random string with only certain characters allowed to repeat in python
Okay, I'm trying to generate a 10 character string containing specific characters. 好的,我正在尝试生成包含特定字符的10个字符串。 With the conditions being, the letters can NOT be repeats (but the numbers CAN), and the string can ONLY contain a total of TWO letters, no more, no less.
在这种情况下,字母不能重复(但数字可以重复),并且字符串只能包含总共两个字母,不能多也不能少。 The final string output MUST be 8 numbers, and 2 letters.
最终的字符串输出必须是8个数字和2个字母。
numbers = ["1", "2", "3"]
letters = ["X", "Y", "Z"]
ie the string output should be similar to 即字符串输出应类似于
123X21Y213
The problem is, I don't know how to do this, elegantly. 问题是,我不知道如何做到这一点。 I did create a solution, but it was way too many lines, and it involved constantly checking the previous character of the string.
我确实创建了一个解决方案,但是行太多了,涉及不断检查字符串的前一个字符。 I'm really bad at this, and need something simpler.
我真的很不好,需要一些简单的方法。
Any help would be appreciated. 任何帮助,将不胜感激。
numbers = ["1", "2", "3"]
letters = ["X", "Y", "Z"]
from random import sample, shuffle
samp = sample(letters,2)+sample(numbers*3,8)
shuffle(samp)
print("".join(samp))
113332X2Z2
Or use choice and range: 或使用选择和范围:
from random import sample, shuffle,choice
samp = sample(letters,2)+[choice(numbers) for _ in range(8)]
shuffle(samp)
print("".join(samp))
1212ZX1131
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.