Random string generation with upper case letters a

2018-12-31 06:09发布

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4

How can I achieve this in a pythonic way?

27条回答
临风纵饮
2楼-- · 2018-12-31 07:08

You can use the code

var chars = "ABC123";
        var random = new Random();
        var result = new string(
            Enumerable.Repeat(chars, 7) //Change 7 to any number of characters you want in your outcome
                      .Select(s => s[random.Next(s.Length)])
                      .ToArray());

        textBox1.Text = result;

This will random spit out a random 7 alphanumeric pattern, simply change the 7 to any number you wish and it will produce that many numbers and/or letters.

Another way to write this is as follows...

var chars = "ABC123";
var stringChars = new char[7]; //Change 7 to any number of characters you want in your outcome
var random = new Random();

for (int i = 0; i < stringChars.Length; i++)
{

stringChars[i] = chars[random.Next(chars.Length)];

}

var finalString = new String(stringChars);

textBox1.Text = finalstring;`

I am unsure of how to add restrictions such as making it to where it does not allow certain numbers and/or letters to be next to each other or repeat such as getting "AAA123" if anyone knows how to restrict the outcome to have something like this please comment back

查看更多
唯独是你
3楼-- · 2018-12-31 07:09

Based on another Stack Overflow answer, Most lightweight way to create a random string and a random hexadecimal number, a better version than the accepted answer would be:

('%06x' % random.randrange(16**6)).upper()

much faster.

查看更多
妖精总统
4楼-- · 2018-12-31 07:12

for python 3 import string, random

''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(15))

查看更多
登录 后发表回答