简体   繁体   English

生成一个随机字符串,仅允许某些字符在python中重复

[英]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.

相关问题 在python中生成一个排除某些特殊字符的随机字符串 - Generate a random string excluding certain special characters in python 正则表达式模式匹配字符串,如果仅包含某些允许的字符 - Regex pattern matching string iff it only contain certain allowed characters 使用Python只保留字符串中的某些字符? - Keeping only certain characters in a string using Python? 如何在 Python 中的字符串中只允许数字、字母和某些字符? - How to only allow digits, letters, and certain characters in a string in Python? 遍历字符串,仅返回某些字符。 蟒蛇 - Looping through a string and only returning certain characters. Python 仅当字符在 python 中以特定顺序出现时才从字符串中删除字符 - Remove characters from a string only when they occur in a certain order in python 在 Python 中,如何检查字符串是否只包含某些字符? - In Python, how to check if a string only contains certain characters? 检查字符串的“alpha”部分是否仅包含特定的字符序列 - python - Check that the "alpha" part of a string consists of only a certain sequence of characters - python 如何在现有字符串中生成随机字符? - How to generate random characters within an existing string? 在字符串中的字符之间添加随机字符 (Python) - Adding Random Characters Between Characters in a String (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM