I trying to make a password generator using python. Currently, I just want the program to print random characters from the ascii table. I will later introduce numbers and symbols. I used a for loop to print random character from a range that the user inputs. It works however, when I use the end='' to print the characters on the same line a % shows up. I think it is there to show that it printed a no character. I would like the program to not print the % because later I will add other numbers and symbols.
I tried subtracting 1 from the range of number. What resulted was the same string with a % but 1 less than intended. I also tried creating a while loop that would print while the variable was less than the password number. It also printed the %.
Here is the code:
import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
print(random.choice(letters), end='')
The % print by your shell (may be zsh), it means the string not end by "\n". It's just a reminder from the shell. There is nothing wrong with you. You can just add a print() in the end of your code to print a "\n", and % will not show again.
Try this
characters = list(string.ascii_letters + string.digits + "!##$%^&*()")
def generate_random_password():
## length of password from the user
length = 8
## shuffling the characters
random.shuffle(characters)
## picking random characters from the list
password = []
for i in range(length):
password.append(random.choice(characters))
## shuffling the resultant password
random.shuffle(password)
## converting the list to string
## printing the list
return "".join(password)
Your script works absolutly fine in my side. see this https://onlinegdb.com/9EagkKVW1
If you feel like it's issue with end you can simply concat outputs to string and print at once like so.
import random
import string
letters=string.ascii_letters
pas =''
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
pas += random.choice(letters)
print(pas)
outputs #
How many characters do you want your password to be? 5
AvfYm
we can use the random .sample() method. it requires 2 arguments:
- iterable of elements to use
- number of elements to take
the result does not contain duplicates.
import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
pas = ''.join(random.sample(letters, k=passwordnumber))
print(pas)
Related
What im making
Hi!
Im making a password generator script in Python ( Script below ). and i was wondering what the best way would be to make sure the passwords dont have two of the same character/symbol right after eachother.
as an example:
kjhd8!3JJp-#huwwg
i would like a way within my script to make sure the duplicates arent "touching". if that makes sense (my english isnt very good).
the same password can have the same character, thats fine. but i would like it not to have them "touching"
like:
kjwhd8!3Jp-#huwJg
if that makes sense.
The script
import random
import string
import sys
#amount of passwords to make
amount = 10
# Characters and symbols to use for the password
# ive split it up to make sure it takes from all of the lists
chars ="abcdefghjkmnpqrstuvwxyzABCDEFGHJK"
specials="#####!-----"
digits="2346789"
characters = list(chars + digits + specials)
def generate_random_password():
# length of the passwords
length = 18
# mixes and shuffles the characters
random.shuffle(characters)
# Puts the sections together at random
password = []
for i in range(length):
password.append(random.choice(characters) )
# another shuffle to make sure (probably noy needed but meh)
random.shuffle(password)
# converts to a string
print("".join(password))
# Prints out as many passswords as stated in the "amount" variable
for index in range(amount):
generate_random_password()
You can just check if the generated char is the same that the previous one, if it is: pick another char, else continue.
prev_char=None
for i in range(length):
random_char = random.choice(characters)
while prev_char == random_char:
random_char = random.choice(characters)
password.append(random_char)
prev_char = random_char
You can use a regex for this!
The expression:
(.)\1
What it does:
(.) - group that matches one character
\1 - reference to group 1 (the group above)
What this essentially does is that it looks for a character repeating right after itself.
How to use it?
import re
any(re.findall(r"(.)\1", "kjwhd8!3Jp-#huwJg"))
findall will find any ocurrences of this; any will give you True or False if there are any cases.
Note: You could also extend this so that the same character doesn't repeat within the next let's say 4 characters: (.).{0,4}\1
I'm very new to coding and im learning python and I have a certain problem.
I'm writing a program which requires the user to input an amount and I want the program to always
print out 15 zeros but I want the amount the user inputs to replace the zeros starting from the end.
For example, if the user enters 43525.
The program would print 000000000043525
Also for example if the user inputs 2570.20
The program would print 000000000257020 (removes dot automatically)
can anyone help me with how I should go about doing this?
you can use .replace() to remove any decimal point and .rjust() to add the right number of zeros
print(input('number: ').replace('.', '').rjust(15, '0'))
You can just use simple string manipulations to do this. For example:
k = 212.12
if '.' in str(k):
string = str(k).replace('.','')
print('0'*(15-len(string))+string)
else:
print('0'*(15-len(str(k)))+str(k))
You can use zfill for this:
print(''.join(input('Enter number: ').split('.')).zfill(15))
You can add leading 0s by using this string formatting while printing:
print("%015d" % (int(number),))
This means 0s will be added until 15 characters are printed.
For the removal of decimal dot you can use string replace method:
number = str(number).replace('.', '')
This should get you started.
Using list slicing
added_string = added_string.replace(".", "")
new_str = start_string[:len(start_string) - len(added_str)] + added_string
I'm a beginner in Python and my assignment is to guess the password by running through the length of the unknown, random password and then replacing that position with the correct letter/number. I know it involves running the code until a match is found but I'm stuck.
You are to write a program that will try to guess each position of the password. The program must use a function that contains the code to hack the password.
Use of lists and methods/functions such as list( ) and .join will be helpful.
You should begin by displaying a string made up of asterisks (e.g. *******) equal to the length of the generated password.
As you match each letter/number in the secret password, replace the asterisk in that same position with that letter/number.
The output should look like this:
Password is yfdszk
Hacking...
Found match at position 2
*d****
Found match at position 1
*fd***
Found match at position 5
*fd**k
Found match at position 3
*fds*k
Found match at position 0
yfds*k
Found match at position 4
yfdszk
I did it! yfdszk
Here is my code:
import random
characters="abcdefghijklmnopqrstuvwxyz0123456789"
charList=list(characters)
def generatePassword(pwLen):
pw=""
for i in range(pwLen):
rand=int(random.randint(0,len(charList)-1))
pw=pw + (charList[rand])
pwList = list(pw)
return pw
def hackPassword(pw):
r`enter code here`and=int(random.randint(0,len(charList)-1))
pw=pw + (charList[rand])
pwList = list(pw)
asterisk = "*" * len(pw)
asteriskList = list(asterisk)
print asterisk
for numbers in range(len(charList)):
if charList == pwList[]:
password = pw[:index] + "*" + pw[index+1:]
password=generatePassword(8)
# display secret
print "Password is " + password
hackPassword(password)
I need to be able to guess the password, using a for loop to go through the length of the password, then finding a match, and then replacing that asterisk with the found letter/number.
But I'm getting this error message:
IndexError: list index out of range on line 20
Although your sample run is flawed, I believe I understand the gist of what you're trying to do. You generate a random password and then represent it with asterisks, so that the length is shown. Then, for each character in characters="abcdefghijklmnopqrstuvwxyz0123456789" you check if it matches any of the chars in the password. By the time you've run through it, you're done. So, you're going to need a double nested loop. I won't write it for you, but i'll give you a hint, in pseudocode:
generate a random password
make a corresponding 'fake' password of the same length of asterisks
for char in charList:
for position in actual password:
if char matches that position:
change the asterisk to that char in the fake password
if my fake password is cracked (no more asterisks):
print('Whoohoo!')
go home, you're done
Hope this helps! Getting the logic right is always the hardest part of programming!
As a side note, I got the above understanding because I noticed in your example that you are cracking the password in alphabetical order... d-f-k-s-y-z...
I was trying to make a program that could be used for one-time pad encryption by counting the number of characters and having a random number for each one. I started making a line that would let the program ignore spaces, but then I realized I would also need to ignore other symbols. I had looked at How to count the number of letters in a string without the spaces? for the spaces,
and it proved very helpful. However, the answers only show how to remove one symbol at a time. To do what I would like by using that answer, I would have to have a long line of - how_long.count('character')'s, and symbols that I may not even know of may still be copied in. Thus, I am asking for a way where it will only count all the alphabetic characters I write down in a list. Is this possible, and if so, how would it be done?
My code:
import random
import sys
num = 0
how_long = input("Message (The punctuation will not be counted)\n Message: ")
charNum = len(how_long) - how_long.count(' ')
print("\n")
print("Shift the letters individually by their respective numbers.")
for num in range(0, charNum-1):
sys.stdout.write(str(random.randint(1, 25))+", ")
print(random.randint(1, 25))
If your desired outcome is to clean a string so it only contains a desired subset of characters the following will work but, I'm not sure I totally understand what your question is so you will probably have to modify somewhat.
desired_letters = 'ABCDOSTRY'
test_input = 'an apple a day keeps the doctor away'
cleaned = ''.join(l for l in test_input if l.upper() in desired_letters)
# cleaned == 'aaadaystdoctoraay'
Use Regex to find the number of letters in the input:
import re, sys, random
how_long = input("Message (The punctuation will not be counted)\n Message: ")
regex_for_letters = "[A-Za-z]"
letter_count = 0
for char in how_long:
check_letter = re.match(regex_for_letters, char)
if check_letter:
letter_count += 1
print(letter_count)
for num in range(0, letter_count-1):
sys.stdout.write(str(random.randint(1, 25))+", ")
print(random.randint(1, 25))
Filter the string:
source_string='My String'
allow_chars=['a','e','i','o','u'] #whatever characters you want to accept
source_string_list=list(source_string)
source_string_filtered=list(filter(lambda x: x in allow_chars,source_string_list))
the count would be: len(source_string_filtered)
# !/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
import itertools
import enchant
d = enchant.Dict("en_GB")
jword = input(str("Enter Word Here:-"))
lword = list(jword)
n = len(jword)
mword = itertools.permutations([lword],n)
if d.check(mword):
print (mword)
else:
print("Invalid input")
So this is the program I made. What I meant it to do was take an input (jword) and the make a list out of it and then check all the possible permutations of that list where the length of the permutation is the length of the original word.
After that it should check whether any of the permuted words is an English word using pyenchant. If it is, print that word, and if it is not, print "Invalid input".
input for python3
raw_input for python2
Your final print statement also has one indent too many.