I'm new to programming and trying to learn it by doing small projects. Currently I'm working on a random string generator and I have it 99% done, but I cant get the output to be the way I want it to be.
First, here is the code:
import random
def pwgenerator():
print("This is a randomm password generator.")
print("Enter the lenght of your password and press enter to generate a password.")
lenght = int(input())
template = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!" # this is the sample used for choosing random characters
generator = ""
for x in range(lenght): # join fcuntion goes trough str chronologically and I want it fully randomized, so I made this loop
add_on = str(random.sample(template, 1))
generator = generator + add_on
#print(add_on) added this and next one to test if these are already like list or still strings.
#print(generator)
print(generator) # I wanted this to work, but...
for x in range(lenght): #...created this, because I thought that I created list with "generator" and tried to print out a normal string with this
print(generator[x], end="")
pwgenerator()
The original code was supposed to be this:
import random
def pwgenerator():
print("This is a randomm password generator.")
print("Enter the lenght of your password and press enter to generate a password.")
lenght = int(input())
template = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!"
generator = ""
for x in range(lenght):
generator = generator + str(random.sample(template, 1))
print(generator)
pwgenerator()
The problem is that with this original code and an for example an input of 10 I get this result:
['e']['3']['i']['E']['L']['I']['3']['r']['l']['2']
what I would want as an output here would be "e3iELI3rl2"
As you can see in the first code i tried a few things, because it looked to me like i was somehow creating a List with lists as items, that each have 1 entry. So i though I would just print out each item, but the result was (for a user input/lenght of 10):
['e']['3']
So it just printed out each character in that list as a string (inlcuding the brackets and quotation marks) , which I interpret as whatever I created not being a list. but actually still a string
Doing some research - and assuming I still created a string - i found this from W3Schools. If I understand it correctly though Im, doing everything right trying to add strings together.
Can you please tell me whats going on here, specifically why I get the output i get that looks like a list of lists?
And if you can spare some more time Id also like to hear for a better way to do this, but I mainly want to understand whats going on, rather than be given a solution. Id like to find a solution myself. :D
Cheers
PS:
Just in case you are wondering: Im trying to learn by doing and currently follow the suggested mini projects from HERE. But in this case I read on W3Schools, that the "join" method results in chronological results so I added the additional complication of making it really random.
Okay, so the problem is that random.choice returns list of strings instead of a string as you may see below:
template = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!"
random.sample(template, 1)
Out[5]: ['H']
What actually happened there it was adding strings containing result of list casting (e.g ['H'] was converted to "['H']" and then printed on the screen as ['H']).
After modyfying the function to random.choice it worked fine:
random.choice(template)
Out[6]: 'j'
Switch this random.sample to random.choice in your function and it shall be as you expected.
The random.sample() function returns a list chosen from the given string.
That's why you're getting a bunch lists stacked together.
Related
This is in relation to web scraping, specifically scrapy. I want to be able to iterate an expression to create my items. As an example, lets say I import the item class as "item." In order to then store an item, I would have to code something like:
item['item_name'] = response.xpath('xpath')
My response is actually a function so it actually looks something like:
item['item_name'] = eval(xpath_function(n))
This works perfectly. However, how can I iterate this to create multiple items with different names without having to manually name each one? The code below does not work at all (and I didn't expect it to), but should give you an idea of what I am trying to accomplish:
for n in range(1, 10):
f"item['item_name{n}'] = eval(xpath_function(n))"
Basically trying to create 10 different items names item_name1 - item_name10. Hope that makes sense and I appreciate any help.
If you are just creating keys for your dictionary based on the value of n you could try something like:
for n in range(10):
item['item_name' + str(n+1)] = eval(xpath_function(n+1))
If you need to format the number (e.g. include leading zeros), you could use an f-string rather than concatenating the strings as I did.
[NB your for loop as written will only run from 1 to 9, so I have changed this in my answer.]
I have a curve_hex generator, it uses two coordinates, I'm looking for only one coordinate. The script searches for one coordinate value easily, but if I specify several coordinates for the search, then it does not find anything.
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
One value is found normally. But if I add several values, the script writes an error
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
Tell me how to do it right. What am I doing wrong. I have just started learning python.
Very exciting that you are learning python, I would also suggest that you might want to spend some time in the stackoverflow section explaining how to ask a question because I am not 100% sure what you are trying to achieve with your code.
From my understanding, if you are happy with your if else conditions, and your only problem is that you can’t add multiple values to wanted. I would convert wanted to a list that includes all your wanted values, and loop over those.
Something like this:
wanted = ['586..{copy the whole value here}', '108...{copy the value here}']
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
for value in wanted:
if str(curve_hex).find(value)!=-1:
print (curve_hex[str(curve_hex).find(value):str(curve_hex).find(value)+len(value)])
else:
print ('not')
Edit: formatting and typos
You are misleadiong some basic concepts:
Difinitions like this result in diferent types
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
type(wanted) # string
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
type(wanted) # tuple
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
type(wanted) # string
So you should choose a type first. Tuple is the best case.
wanted=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
curve_hex=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
for i in wanted:
for x,j in enumerate(curve_hex):
if i in j:
print(f'{i} in {curve_hex} at position {x}')
This seems like a pretty rudimentary question, but I'm wondering because the items in these lists change every so often when a website is scraped...
employees = ['leadership(x)', 'drivers(y)', 'trainers(z)']
Where x,y,z are the number of employees in those specific roles, and are the values that change every so often.
If I know that the strings will always be 'leadership' 'drivers' and 'trainers', just with a difference in what's in between the parentheses, how can I dynamically remove these strings without having to hardcode it every week that I run the program?
The obvious but not so successful solution is...
employees = ['leadership(x)', 'drivers(y)', 'trainers(z)']
unwanted = ['leadership(x)', 'drivers(y)', 'trainers(z)']
for i in unwanted:
if i in employees:
employees.remove(i)
This of course fails because the values are hardcoded and the values are bound to change, any help with this would be greatly appreciated!
You could do something like
unwanted_prefixes = ['leadership', 'drivers', 'trainers']
unwanted = [s for s in employees if s.split('(')[0] in unwanted_prefixes]
This will make the list of things to delete contain any string beginning with those 3 prefixes and either containing nothing else or immediately followed by a parenthesis.
A more complicated solution, if that one deletes strings that you want, that follows roughly the same idea, but with a regex:
import re
unwanted_re = re.compile(r'(leadership|drivers|trainers)\(\d+\)')
unwanted = [x for x in employees if unwanted_re.fullmatch(x)]
I have a program where I would like to randomly pull a line from a song, and string them together with other lines from other songs. Looking into I saw that the dateutil library might be able to help me parse multiple variables from a string, but it doesn't do quite what I want.
I have multiple strings like this, only much longer.
"This is the day\nOf the expanding man\nThat shape is my shade\nThere where I used to stand\nIt seems like only yesterday\nI gazed through the glass\n..."
I want to randomly pull one line from this string (To the page break) and save it as a variable but iterate this over multiple strings, any help would be much appreciated.
assuming you want to pull one line at random from the string you can use choice from the random module.
random. choice ( seq ): Return a random element from the non-empty
sequence seq. If seq is empty, raises IndexError.
from random import choice
data = "This is the day\nOf the expanding man\nThat shape is my shade\nThere where I used to stand\nIt seems like only yesterday\nI gazed through the glass\n..."
my_lines = data.splitlines()
my_line = choice(my_lines)
print(my_line)
OUTPUT
That shape is my shade
Pretty much I'm trying to make a GPA calculator. I don't want anyone to just do the whole thing for me because I'm trying to figure out how to get 8 different values from the user in one line and add them together into one value. Most of the answers I've found online only talk about adding 2 values together so it's not of very much use to me...
I've tried using the ".split" function but really that's about it I'm new to python and dont have the background knowledge to really try much else.
No code, just need help with this problem
The expected result is to ask the user to put in 8 different grades between 0 and 100, then add them together into one value to later be divided.
If the GPAs come in in this format:
'3.3 3.6 2.7'
then you can read it in like this:
gpas = input('Please enter the GPAs in one line separated by spaces').split(' ')
and then you can loop through them (since split() returns a list), convert them to floats, and add them up, like so:
sum = 0
for gpa in gpas:
sum += float(gpa)
From what I read, I see you're getting the user's input as a string, from what you want to get the numbers the user entered and then operate with them, your problem being getting each separate number from the input. I think this other question on SO may help. Once you get each 'word' as an element of the array, you should convert each element to an int, getting the desired result.
Hope this helps!