Inserting breaks in variables over a certain length - python

So basically what I want to do is if the random string of characters generated is over 6 chars long it adds a space in a random place in that string and then the remaining ones are added on after the space so for example: raw output: "aoneicse", what I want : "aoneic se" or "aone icse".
Here is my code:
import random
alist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
blist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
clist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# define the 3 words
a = ''.join(random.choices(alist, k = random.randint(2,8)))
b = ''.join(random.choices(blist, k = random.randint(2,8)))
c = ''.join(random.choices(clist, k = random.randint(2,8)))
# each letter is a certain word, if this word exceeds 6 characters add a space in a random place
if a length = > 6:
asp = [a + " "]
if b length = > 6:
bsp = [b + " "]
if c length = > 6:
csp = [c + " "]
# or something along the lines of this i guess
This code does not currently work, BTW.

You don't need to create a list of strings with every letter of the alphabet, there's already a string module that does that for you:
import string
print(' ' + string.ascii_lowercase)
# Outputs abcdefghijklmnopqrstuvwxyz
You also don't need to create three different variables, you can just use a single one and use that:
import string
base_str = ' ' + string.ascii_lowercase
Then, you can use a list to generate your words based on this string:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
Now, just apply your space requirement to each word:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
new_words = []
for word in words:
if len(word) < 6:
new_word = word
else:
pos = random.randrange(len(word))
new_word = word[:pos] + ' ' + word[pos:]
new_words.append(new_word)
Using random.seed(0), new_words is equal to ['j xazmxvz', 'oxmg', 'buzns pcb'].

Don't join the choices immediately. Generate the list, and if it is long enough, pick an index in the middle (sufficiently far from either end, depending on your needs), and perform a slice assignment to the empty list at that position. Then join the list into a single string.
import string
a = random.choices(string.ascii_lowercase, k=random.randint(2,8))
if len(a) > 6:
# Adjust the arguments to randint as desired
x = random.randint(2, len(a) - 2)
a[x:x] = ' '
a = ''.join(a)

import random
character = list(map(chr, range(ord('a'), ord('z') + 1)))
def get_char():
return character[random.randint(0, len(character) - 1)]
def gen_word(min_len, max_len):
word = [get_char() for _ in range(random.randint(min_len, max_len))]
if len(word) > 6:
word[random.randint(1, len(word) - 2)] = ' '
return ''.join(word)
for i in range(10):
print(gen_word(4, 10))

I’d use slices to return a space, sliced-in at the right spot; Something along the lines of:
def split(input_str):
if len(input_str) > 6:
space_at = rand(0,len(input_str))
return input_str[:space_at] + ‘ ‘ + input_str[space_at:]
else:
return input_str

Related

TypeError: can only concatenate str (not "int") to str (I don't think that should happen)

I decided it would be a cool idea to make a translator to a custom language, so I tried making one. However, I am fairly new to python, and I cannot figure out why it is expecting a string instead of an integer. What I am trying to do is make it so if you enter in a word such as 'bin', it will go to the next consonant/vowel for each, so 'bin' ends up as 'cop' as the next consonant after 'b' is 'c', the next vowel after 'i' is 'o' and the next consonant after 'n' is 'p'.
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
translated_word = ''
word_to_translate = input('Enter in the word to translate! ')
for letter in range(len(word_to_translate)):
new_letter = word_to_translate[letter - 1]
if new_letter in consonants:
l = (consonants[:new_letter + 1])
translated_word = translated_word + str(l)
elif new_letter in vowels:
l = (vowels[:new_letter + 1])
translated_word = translated_word + str(l)
print(translated_word)
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
translated_word = ''
word_to_translate = input('Enter in the word to translate! ')
for i in word_to_translate:
if i in consonants:
ind = consonants.index(i)
translated_word += consonants[ind+1]
elif i in vowels:
ind = vowels.index(i)
translated_word += vowels[ind+1]
print (translated_word)

How to write code that checks to see if item is negative before split?

Hey so I have a polyalphabetic cipher and it's working great but I am running into the issue of having all my inputs on one line. The inputs would be the shift;secretWord; and message. I need to find a way to check if an input is solely a negative number and if it is I need the code to exit. I also need to find a way to make my code keep looping until the negative condition is met.
alpha = ['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']
shiftChange = 0
secretWord = 0
da_message = 0
shiftChange = int(shiftChange)
inputs = []
shiftChange, secretWord, da_message = input('').split(";")
da_message = da_message.lower()
inputs.append(shiftChange)
inputs.append(secretWord)
inputs.append(da_message)
secretWord = secretWord.lower()
secretWord = secretWord * len(da_message)
cypherText = ''
symbol = ' '
count = 0
for letter in da_message:
if letter in alpha:
shift = alpha.index(secretWord[count]) + int(shiftChange)
letterIndex = alpha.index(letter) + 1
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count + 1
print(cypherText.upper())
Use int().
The int() raises a ValueError for anything that isn't, entirely, an integer. Trap this error using a try-except loop and then if the error is raised, then execute the rest of your code. (since it is an alphanumeric) Otherwise, compare it if it is less than 0 and exit if true.
Below is a modified version of your code that solves both of your problems.
The while True ensures the program continues to loop until the negative number is found, which in turn causes it to exit the entire program.
alpha = ['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']
shiftChange = 0
secretWord = 0
da_message = 0
cypherText = ''
symbol = ' '
count = 0
shiftChange = int(shiftChange)
inputs = []
while True:
shiftChange, secretWord, da_message = input('enter:').split(";")
da_message = da_message.lower()
inputs.append(shiftChange)
inputs.append(secretWord)
inputs.append(da_message)
secretWord = secretWord.lower()
secretWord = secretWord * len(da_message)
for i in range(len(inputs)):
try:
temp = int(inputs[i])
except ValueError:
for letter in da_message:
if letter in alpha:
shift = alpha.index(secretWord[count]) + int(shiftChange)
letterIndex = alpha.index(letter) + 1
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count + 1
print(cypherText.upper())
if temp < 0:
exit()
Hope this helps!

Append dot before each letters

I want to add a point before each letter.
Unfortunately, the point is after each letter. How to insert the point before each letter?
myText = str(input())
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ''
for letter in myText:
if letter not in vowels:
result = result + letter
for i in result:
result = result + '.'
break
print(result.lower())
A shorter and faster solution relying on the power of regular expressions:
import re
my_text = "sample"
re.sub(r"[aeiou]*([^aeiou])[aeiou]*", r".\1", my_text.lower())
This reads: “delete vowels, and prefix each remaining letter with a dot”.
Removing all vowels and append "." before each letter.
myText = "sample"
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ''
for letter in myText:
if letter not in vowels:
result = result + '.' + letter
print(result.lower())
# .s.m.p.l
Fian's answer is probably the best one. Here's my attempt:
text = 'audfijsdfmsomlasn'
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
result = ''
for letter in text:
if letter in vowels:
result += '.'
result += letter
print(result)
Yet another way:
import re
myText = "sample"
result = '.' + '.'.join(list(re.sub('[aeiou]', "", myText, flags=re.I)))
print(result)
Explanation:
re.sub removes the not required letters (case insensitive = re.I)
list makes the string an array of characters
join places a dot in between
'.' + adds the missing dot in front of the first character
string = input()
vowels = ['a', 'A', 'i', 'I', 'o', 'O', 'u', 'U', 'e', 'E']
translation = string.maketrans({i: '' for i in vowels})
string = string.translate(translation)
result = ''
for letter in string:
result = result + '.' + letter
print(result.lower())

Python Password Generator

I am trying to create a password generator in Python that must contain an uppercase letter, lowercase letter, and a number, and must have a length between 6 and 20 characters.
import random
import string
def password_gen():
while True:
length = random.randint(6,20)
pwd = []
for i in range(length):
prob = random.random()
if prob < 0.34:
char = random.choice(string.ascii_lowercase)
pwd.append(char)
elif prob < 0.67:
char = random.choice(string.ascii_uppercase)
pwd.append(char)
else:
char = str(random.randint(0,9))
pwd.append(char)
pwd = ''.join(pwd)
#check password here
return pwd
However, I am having trouble checking the password to make sure it contains the required characters listed earlier. I am not sure if/how i would use a continue statement.Any help would be greatly appreciated!
I think this would be a bit easier to ensure you meet the base requirements if you just handle those upfront.
import random
import string
def generate_pw():
length = random.randint(6,20) - 3
pwd = []
pwd.append(random.choice(string.ascii_lowercase))
pwd.append(random.choice(string.ascii_uppercase))
pwd.append(str(random.randint(0,9)))
# fill out the rest of the characters
# using whatever algorithm you want
# for the next "length" characters
random.shuffle(pwd)
return ''.join(pwd)
This will ensure your password has the characters you need. For the rest of the characters you could for example just use a list of all alphanumeric characters and call random.choice length times.
you can use isupper() and islower() functions to get does your password contain uppercase and lowercase.
e.g.
upper=0
lower=0
for i in range(length):
if (pwd[i].islower()):
upper=1
elif (pwd[i].isupper()):
lower=1
import random
import string
def password_gen():
lower_case_letter = random.choice(string.ascii_lowercase)
upper_case_letter = random.choice(string.ascii_uppercase)
number = random.choice(string.digits)
other_characters = [
random.choice(string.ascii_letters + string.digits)
for index in range(random.randint(3, 17))
]
all_together = [lower_case_letter, upper_case_letter] + other_characters
random.shuffle(all_together)
return ''.join(all_together)
Password Generator more broken down, you can get any number you wish, but it outputs a pattern by first adding letters, then numbers and finally symbols
import random
letters = ['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', '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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
passwordlength = nr_letters + nr_numbers + nr_symbols
chars = ""
for x in range (0, nr_letters):
char = random.choice(letters)
chars += char
nums = ""
for y in range (0, nr_numbers):
num = random.choice(numbers)
nums+=num
syms = "" # string accumulator
for z in range (0, nr_symbols):
symb = random.choice(symbols)
syms += symb
print(f"Here is your password: {chars}{nums}{syms}")

Python: how to print range a-z?

1. Print a-n: a b c d e f g h i j k l m n
2. Every second in a-n: a c e g i k m
3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}: hello.com/a hej.com/b ... hallo.com/n
>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'
To do the urls, you could use something like this
[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]
Assuming this is a homework ;-) - no need to summon libraries etc - it probably expect you to use range() with chr/ord, like so:
for i in range(ord('a'), ord('n')+1):
print chr(i),
For the rest, just play a bit more with the range()
Hints:
import string
print string.ascii_lowercase
and
for i in xrange(0, 10, 2):
print i
and
"hello{0}, world!".format('z')
for one in range(97,110):
print chr(one)
Get a list with the desired values
small_letters = map(chr, range(ord('a'), ord('z')+1))
big_letters = map(chr, range(ord('A'), ord('Z')+1))
digits = map(chr, range(ord('0'), ord('9')+1))
or
import string
string.letters
string.uppercase
string.digits
This solution uses the ASCII table. ord gets the ascii value from a character and chr vice versa.
Apply what you know about lists
>>> small_letters = map(chr, range(ord('a'), ord('z')+1))
>>> an = small_letters[0:(ord('n')-ord('a')+1)]
>>> print(" ".join(an))
a b c d e f g h i j k l m n
>>> print(" ".join(small_letters[0::2]))
a c e g i k m o q s u w y
>>> s = small_letters[0:(ord('n')-ord('a')+1):2]
>>> print(" ".join(s))
a c e g i k m
>>> urls = ["hello.com/", "hej.com/", "hallo.com/"]
>>> print([x + y for x, y in zip(urls, an)])
['hello.com/a', 'hej.com/b', 'hallo.com/c']
import string
print list(string.ascii_lowercase)
# ['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']
import string
print list(string.ascii_lowercase)
# ['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']
and
for c in list(string.ascii_lowercase)[:5]:
...operation with the first 5 characters
myList = [chr(chNum) for chNum in list(range(ord('a'),ord('z')+1))]
print(myList)
Output
['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']
list(string.ascii_lowercase)
['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']
Try:
strng = ""
for i in range(97,123):
strng = strng + chr(i)
print(strng)
import string
string.printable[10:36]
# abcdefghijklmnopqrstuvwxyz
string.printable[10:62]
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))
#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))
#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]
The answer to this question is simple, just make a list called ABC like so:
ABC = ['abcdefghijklmnopqrstuvwxyz']
And whenever you need to refer to it, just do:
print ABC[0:9] #prints abcdefghij
print ABC #prints abcdefghijklmnopqrstuvwxyz
for x in range(0,25):
if x % 2 == 0:
print ABC[x] #prints acegikmoqsuwy (all odd numbered letters)
Also try this to break ur device :D
##Try this and call it AlphabetSoup.py:
ABC = ['abcdefghijklmnopqrstuvwxyz']
try:
while True:
for a in ABC:
for b in ABC:
for c in ABC:
for d in ABC:
for e in ABC:
for f in ABC:
print a, b, c, d, e, f, ' ',
except KeyboardInterrupt:
pass
This is your 2nd question: string.lowercase[ord('a')-97:ord('n')-97:2] because 97==ord('a') -- if you want to learn a bit you should figure out the rest yourself ;-)
I hope this helps:
import string
alphas = list(string.ascii_letters[:26])
for chr in alphas:
print(chr)
About gnibbler's answer.
Zip -function, full explanation, returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. [...] construct is called list comprehension, very cool feature!
# Assign the range of characters
first_char_start = 'a'
last_char = 'n'
# Generate a list of assigned characters (here from 'a' to 'n')
alpha_list = [chr(i) for i in range(ord(first_char), ord(last_char) + 1)]
# Print a-n with spaces: a b c d e f g h i j k l m n
print(" ".join(alpha_list))
# Every second in a-n: a c e g i k m
print(" ".join(alpha_list[::2]))
# Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}
# Ex.hello.com/a hej.com/b ... hallo.com/n
#urls: list of urls
results = [i+j for i, j in zip(urls, alpha_list)]
#print new url list 'results' (concatenated two lists element-wise)
print(results)
Another way to do it
import string
aalist = list(string.ascii_lowercase)
aaurls = ['alpha.com','bravo.com','chrly.com','delta.com',]
iilen = aaurls.__len__()
ans01 = "".join( (aalist[0:14]) )
ans02 = "".join( (aalist[0:14:2]) )
ans03 = "".join( "{vurl}/{vl}\n".format(vl=vlet,vurl=aaurls[vind % iilen]) for vind,vlet in enumerate(aalist[0:14]) )
print(ans01)
print(ans02)
print(ans03)
Result
abcdefghijklmn
acegikm
alpha.com/a
bravo.com/b
chrly.com/c
delta.com/d
alpha.com/e
bravo.com/f
chrly.com/g
delta.com/h
alpha.com/i
bravo.com/j
chrly.com/k
delta.com/l
alpha.com/m
bravo.com/n
How this differs from the other replies
iterate over an arbitrary number of base urls
cycle through the urls using modular arithmetic, and do not stop until we run out of letters
use enumerate in conjunction with list comprehension and str.format

Categories

Resources