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'
Related
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'
I have come up with the following code but unfortunately its only removing 1 character from my string.
import random
string = 'HelloWorld!'
def remove_random_character(phrase):
character_number = random.randint(0, len(phrase))
remover = f'{phrase[:character_number - 1]}_{phrase[character_number:]}'
for _ in range(8):
sliced_phrase = remover
print(sliced_phrase)
remove_random_character(string)
I thought that the for loop will take care of this but unfortunately it did not. but every time it loops it just refreshes the sliced_phrase variable. but I do not know how to store the last version of the loop, for that to be edited. So how can I can I remove multiple random characters from a string?
You can iterate over every letter in your string and decide do you need to remove it:
import random
string = 'HelloWorld!'
output = ''.join([s for s in string if random.random() < 0.7])
Test:
Heloold!
elloWld!
loWorld
import random
def remove_random_char(string):
char_index_to_remove = random.randint(0, len(string)-1)
string = string.replace(string[char_index_to_remove], '', 1)
return string
string = 'HelloWorld!'
times_to_iterate = 4
for i in range(times_to_iterate):
string = remove_random_char(string)
What about:
import random
def remove_random_character(phrase, n_remove):
for num in random.sample(range(0, len(phrase)), n_remove):
phrase = phrase[:num] + '_' + phrase[num + 1:]
return phrase
Then to remove, say, 3 random characters:
string = 'HelloWorld!'
new_phrase = remove_random_character(string, 3)
import random
phrase = 'HelloWorld!'
num_of_missing_chars = 4
def random_char_remover(string: str, num_missing_char: int):
def index_remover(string: str):
char_index_to_remove = random.randint(0, len(string)-1)
string = string.replace(string[char_index_to_remove], '_', 1)
return string
for i in range(num_missing_char):
string = index_remover(string)
print(string)
random_char_remover(phrase, num_of_missing_chars)
Thanks guys this is what I got finally after reviewing all your answers and using a bit of all of them. it may be a little simplified from my end but I only work with code that I can understand.
:)
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))
Given a number number such that its digits are grouped into parts of length n (default value of n is 3) where each group represents some ascii value, I want to convert number into a string of those ascii characters. For example:
n number Output
==================================
3 70 F
3 65066066065 ABBA
4 65006600660065 ABBA
Note that there is no leading 0 in number, so the first ascii value will not necessarily be represented with n digits.
My current code looks like this:
def number_to_string(number, n=3):
number = str(number)
segment = []
while number:
segment.append(number[:n])
number = number[n:]
return str(''.join('{:0>{}}'.format(chr(segment), n) for segment in number))
Expected outputs:
number_to_string(70)
'F'
number_to_string(65066066065)
'ABBA'
number_to_string(65006600660065, n=4)
'ABBA'
My current code however returns an empty string. For example, instead of 'F' it returns ' '. Any reason why this is? Thank you!
P.S.:
I'm wanting to reverse the process of this question, i.e. turn an integer into a string based on the ascii values of each character (number) in the string. But reading that question is not a requirement to answer this one.
Try this:
import re
def number_to_string(num, n=3):
num_str = str(num)
if len(num_str) < n:
num_str = '0' * (n-len(num_str)) + num_str
elif len(num_str) % n != 0:
num_str = '0'*(n-len(num_str)%n) + num_str
print(num_str)
chars = re.findall('.'*n, num_str)
l = [chr(int(i)) for i in chars]
return ''.join(l)
First pad the given number (converted into string) with required number of zeros, so that it can be evenly split into equal number of characters each. Then using re split the string into segments of size n. Finally convert each chunk into character using chr, and then join them using join.
def numToStr(inp):
"""Take a number and make a sequence of bytes in a string"""
out=""
while inp!=0:
out=chr(inp & 255)+out
inp=inp>>8
print "num2string:", out
return out
does this help?
Is this what you want?
def num_to_string(num, leng):
string = ""
for i in range(0,len(str(num)),leng):
n = str(num)[i:i+2]
string += chr(int(n))
print string
Output:
>>> ================================ RESTART ================================
>>>
>>> num_to_string(650065006600,4)
AAB
>>> num_to_string(650650660,3)
AAB
>>> num_to_string(656566,2)
AAB
>>>
You can just append \x to number as this prints 'p':
print '\x70'
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.