How do you create a random string in Python?
I needed it to be number then character repeat till you"re done this is what I created
def random_id(length): number = "0123456789" alpha = "abcdefghijklmnopqrstuvwxyz" id = "" for i in range(0,length,2): id += random.choice(number) id += random.choice(alpha) return id
Random strings in Python repeat: Questions
Create list of single item repeated N times
I want to create a series of lists, all of varying lengths. Each list will contain the same element
n times (where
n = length of the list).
How do I create the lists, without using a list comprehension
[e for number in xrange(n)] for each list?
You can also write:
[e] * n
You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.
At first glance it seems that repeat is the fastest way to create a list with n identical elements:
>>> timeit.timeit("itertools.repeat(0, 10)", "import itertools", number = 1000000) 0.37095273281943264 >>> timeit.timeit(" * 10", "import itertools", number = 1000000) 0.5577236771712819
But wait - it"s not a fair test...
>>> itertools.repeat(0, 10) repeat(0, 10) # Not a list!!!
itertools.repeat doesn"t actually create the list, it just creates an object that can be used to create a list if you wish! Let"s try that again, but converting to a list:
>>> timeit.timeit("list(itertools.repeat(0, 10))", "import itertools", number = 1000000) 1.7508119747063233
So if you want a list, use
[e] * n. If you want to generate the elements lazily, use
What is the best way to repeatedly execute a function every x seconds?
I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.
while True: # Code executed here time.sleep(60)
Are there any foreseeable problems with this code?
If your program doesn"t have a event loop already, use the sched module, which implements a general purpose event scheduler.
import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print("Doing stuff...") # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run()
If you"re already using an event loop library like
kivy, and many others - just schedule the task using your existing event loop library"s methods, instead.
Lock your time loop to the system clock like this:
import time starttime = time.time() while True: print "tick" time.sleep(60.0 - ((time.time() - starttime) % 60.0))