Generating random characters in Python - python

I would like to generate a 16 character code
The code has 5 known characters
The code has 3 digits
The code must be random
What I did :
result1 = "NAA3U" + ''.join((random.choice(string.ascii_uppercase + string.digits) for codenum in range(11)))

One approach:
import random
import string
# select 2 digits at random
digits = random.choices(string.digits, k=2)
# select 9 uppercase letters at random
letters = random.choices(string.ascii_uppercase, k=9)
# shuffle both letters + digits
sample = random.sample(digits + letters, 11)
result = "NAA3U" + ''.join(sample)
print(result)
Output from a sample run
NAA3U6MUGYRZ3DEX
If the code needs to contain at least 3 digits, but is not limited to this threshold, just change to this line:
# select 11 uppercase letters and digits at random
letters = random.choices(string.ascii_uppercase + string.digits, k=11)
this will pick at random from uppercase letters and digits.

You can add the remaining 2 digits at the end if it is fine for you like this
import random
import string
result1 = "NAA3U" + ''.join((random.choice(string.ascii_uppercase) for codenum in range(8))) + str(random.randint(10,99))
print(result1)
NAA3URYWMGIHG45

You can use random.choices and random.shuffle then use ''.join like below:
>>> import random
>>> import string
>>> def generate_rndm():
... digit_char = random.choices(string.ascii_uppercase, k=9) + random.choices(string.digits, k=2)
... random.shuffle(digit_char)
... return "NAA3U" + ''.join(digit_char)
Output:
>>> generate_rndm()
'NAA3UTVQG8DT8NRM'
>>> generate_rndm()
'NAA3UCYBWCNQ45HR'
>>> generate_rndm()
'NAA3UIJP7W7DLOCQ'

Related

combine multiple outputs in python

I am a noob and was wondering how to combine multiple outputs into one string that outputs
Here is my code
print ("password size (use numbers)")
passwordsize = int(input(""))
passwordsize = passwordsize -1
papers = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','?','!','1','2','3','4','5','6','7','8','9','0',]
q_list = [random.choice(papers) for i in range(passwordsize)]
' '.join(q_list)
poopers = q_list[0].replace("'", '')
print("/")
print(q_list)
for word in q_list:
result = word.replace("'", '')
print(result)
lets say that the random stuff picked was 3 a b c
it outputs...
3
a
b
c
I want it to output...
3abc
Any help is very much appreciated
Along the same lines as what #Chuck and #Ash proposed, but streamlining things a bit by taking fuller advantage of Python's standard library as well as the handy join string method:
import random
import string
passwordsize = 4 # int(input()) - 1
a = [*string.ascii_uppercase, *string.digits, "?", "!"]
print("".join(random.sample(a, passwordsize)))
Output:
W16H
import random
passwordsize = 4 # int(input("")) - 1
papers = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z','?','!','1','2','3','4','5','6','7','8','9','0',]
q_list = [random.choice(papers) for i in range(passwordsize)]
result = ""
for word in q_list:
result += word
print(result)
String object in python can use add "+" operation to do concatenation.
For example, if you want to create s = "ABC", you can create it by s = 'A' + 'B' + 'C'.
The += operation can iteratively do the + operation.
Thus, you can create "ABC" by a for loop:
s = ""
for w in ['A', 'B', 'C']:
s += w
If you want every generated char is unique, use random.sample. But if you want every char can occur more than one, use random.choices instead:
from random import choices; from string import ascii_uppercase as caps, digits as nums
result = ''.join(choices(caps+'?!'+nums,k=int(input('password size (use numbers)\n'))))
print(result)
# password size (use numbers)
# 15
# DK6V1DZOFKA?3HG

Generating a 10-digit password

So I need to generate a 10-digit password (needs to use the random module) that must contain 2 lower ase letters, 2 uppercase letters, 3 special symbols and 3 numbers all in a random order every time. I've got the random password generator part done but I'm not sure how to restrict it to 2 lower case letters, 2 upper case letters, 3 special symbols and 3 numbers.
This is what I have so far:
import random
import string
lc_letter = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
uc_letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
symbols = ["!","#","#","$","%","^","&","*","(",")","_","+","=","-","/",">","<",",",".","?","\\"]
numbers = ["0","1","2","3","4","5","6","7","8","9"]
options = [lc_letter,uc_letter,symbols,numbers]
for i in range(10):
choice = random.choice(options)
digit = random.choice(choice)
print(digit, end = '')
You can use constants from string:
import random
import string
s = ""
for i in range(2):
s = s + random.choice(string.ascii_lowercase)
for i in range(2):
s = s + random.choice(string.ascii_uppercase)
for i in range(3):
s = s + random.choice(string.punctuation)
for i in range(3):
s = s + random.choice(string.digits)
s = ''.join(random.sample(s, 10))
print(s)
An alternative approach that I will suggest is, Take 2 letters from uppercase, lowercase etc. and then shuffle resulting password using random.shuffle method.
Pick every needed characters first, then shuffle them:
from random import choice as rd
from random import shuffle
import string
lc_letter = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
uc_letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
symbols = ["!","#","#","$","%","^","&","*","(",")","_","+","=","-","/",">","<",",",".","?","\\"]
numbers = ["0","1","2","3","4","5","6","7","8","9"]
options = [
rd(lc_letter),
rd(lc_letter),
rd(uc_letter),
rd(uc_letter),
rd(symbols),
rd(symbols),
rd(symbols),
rd(numbers),
rd(numbers),
rd(numbers),
]
shuffle(options)
print(''.join(options))
You can use random.choice, random.sample, and constants from the string module to obtain randomly generated passwords.
import random
import string
lc_letter = string.ascii_lowercase
uc_letter = string.ascii_uppercase
# Could use string.punctuation here, but it would be different
# as your list doesn't contain semicolons or colons,
# while string.punctuation does.
symbols = ["!","#","#","$","%","^","&","*","(",")","_","+","=","-","/",">","<",",",".","?","\\"]
numbers = string.digits
lc_selection = [random.choice(lc_letter) for _ in range(2)]
uc_selection = [random.choice(uc_letter) for _ in range(2)]
symbol_selection = [random.choice(symbols) for _ in range(3)]
number_selection = [random.choice(numbers) for _ in range(3)]
print(''.join(random.sample(lc_selection + uc_selection + symbol_selection + number_selection, 10)))
What you can actually do is make a list of length 10 like this:
dist = [0, 0, 1, 1, 2, 2, 2, 3, 3, 3]
This list represents the distribution of each index out of your options list.
For example, you put lowercase letters first in the option, and you have to pick 2 lowercase values, therefore there are 2 zeroes in the distribution list.
Now you can pick an index in the list:
idx = random.randint(0, len(dist))
Then, pick your choice from the list at: options[dist[idx]].
Lastly pop the value at idx from dist.
dist.pop(idx)
This will generate all the valid passwords with the same probability.
An in my opinion better version of Yevgeniy Kosmak's solution (the stand-alone config is clearer to see, the loop avoids code duplication, and using choices instead of choice avoids a loop).
import random
import string
config = [
(2, string.ascii_lowercase),
(2, string.ascii_uppercase),
(3, string.punctuation), # or use your '!##$%^&*()_+=-/><,.?\\'
(3, string.digits),
]
picked = []
for k, options in config:
picked += random.choices(options, k=k)
random.shuffle(picked)
password = ''.join(picked)
print(password)
Try it online!

Generate random string with python for a string(mix of int and chars) with particular lenght

Need to generate random string as follows
first 5 strings should be alphabet in caps
Next 4 should be integers and
one alphabet at last
output i need examples:
ACCE1664Z
BCED1782V
FBCR9126N
it is generating random string.
from string import ascii_uppercase, digits
import random
def generatestr():
str0= random.sample(ascii_uppercase,4)+random.sample(digits,4)+random.sample(ascii_uppercase,1)
return ''.join(str0)
print(generatestr())
Improvement from #ComplicatedPhenomenon's Answer
Visit here for more string constants (e.g. ascii_uppercase).
Suppose the last alphabet is also in caps.
import random
def generatestr():
alphabet = []
for letter in range(65, 91):
alphabet.append(chr(letter))
num = [str(i) for i in range(10)]
str0= random.sample(alphabet,4)+random.sample(num,4)+random.sample(alphabet,1)
return ''.join(str0)
generatestr()
import random
import string
def randomString(charLength, intLength):
letters = string.ascii_uppercase
numbers = list(range(0,9))
charArray = ""
numArray= ""
for i in range(max(charLength,intLength)):
if i < charLength:
charArray = charArray + random.choice(letters)
if i < intLength:
numArray = numArray + str(random.choice(numbers))
return (charArray + numArray + random.choice(letters))
print(randomString(5,4))

How to insert number every nth letter in a string in Python?

I'm writing a program to encrypt a string input. I have a random number generator, and some code that converts the random number into a letter. How would I go about inserting this letter after every say, 3rd letter? I.e. String before: abcdef , String after: abcldefk.
Code for the random number generator if it helps:
Letter = random.randrange(1,26)
print chr(Letter + ord('A'))
You can use str.join, enumerate with a start index equal to 1 and modulo:
print("".join([x if i % 3 else x + random_letter for i, x in enumerate(s,1)]))
If you just want to insert a random letter, you can use string.ascii_letters and random.choice:
from random import choice
from string import ascii_letters
s = "abcdef"
print("".join([x if i % 3 else x + choice(ascii_letters) for i, x in enumerate(s,1)])
abcQdefN
I was inspired by Padraic's answer and wanted to add a little bit more.
import random
Letter = random.randrange(1,26)
def encrypt_string(string, n):
return ("".join([x if i % n else chr(Letter + ord('A')) for i, x in enumerate(string)]))
Here is a string "encryption" (using it loosely) method for every 'nth' letter.
Results (Answers may vary due to random):
print(encrypt_string("0123456789", 2)) # Every other letter
M1M3M5M7M9
print(encrypt_string("0123456789", 3)) # Every third letter
D12D45D78D
I hope this helped.

Generate a random string with a random number of letters and spaces

I have written a function that returns a random string of length n.
import string, random
def randomString(N):
return ''.join(random.sample(string.ascii_lowercase + ' ', N))
However, this only ever returns a string with one of each letter/space. I need a string with a random number of lowercase letters and spaces (characters can repeat).
I have tried adding another argument to the .join method and it returns a syntax error.
How can I change this function to produce a random number of letters and spaces?
from random import choice
from string import ascii_lowercase
# vary the number of spaces appended to adjust the probability
chars = ascii_lowercase + " " * 10
def random_string(n):
return "".join(choice(chars) for _ in range(n))
then
>>> print(random_string(15))
fhr qhay nuf u
As with the number of spaces, you can adjust the number of times each char appears to change its relative probability:
chars = (
' !,,,,,--....'
'.....:;aaaaaaaaaaaaaaaaaaaaabbbbbcccccccccdddddddddeeeeeeeee'
'eeeeeeeeeeeeeeeeeeeefffffggggghhhhhhhhhiiiiiiiiiiiiiiiiiiijj'
'klllllllllmmmmmmnnnnnnnnnnnnnnnnnnooooooooooooooooppppppwrrr'
'rrrrrrrrrrrrrssssssssssssssssttttttttttttttttttttuuuuuuuvvvw'
'wwxyyyyz'
)
for _ in range(5):
print(random_string(30))
gives
sxh ehredi clo-ioodmttlpoir.wo
ijr thc -o,iepe.pcicfrn.osui.a
et rtl teektet rrecyd.d .bate
aji ueava hahe arv tgnrnt eecs
a ne:tudsdu,nlnhbeirp,oioitt e
You're looking for random.choice
import string, random
def randomString(N):
return ''.join(random.choice(string.ascii_lowercase + ' ') for i in range(N))
You can very easily do this with a simple loop, using random.choice rather than random.sample to do it all at once:
>>> import string, random
>>> def random_string(n):
... count = 0
... s = ''
... while count < n:
... s += random.choice(string.ascii_lowercase + ' ')
... count += 1
... return s
...
>>> random_string(27)
'amwq frutj nq dbotgllrbmhnj'
>>> random_string(27)
'khjnmhvgzycqm vyjqcttybuqm '
>>> random_string(27)
'ssakcpeesfe kton gigblmgo o'

Categories

Resources