Here's a quick way to generate a short, random string in Java:
Random r = new Random(); String token = Long.toString(Math.abs(r.nextLong()), 36);
The resultant string is a maximum of ceil(ln(263) / ln(36)) = 13
characters long and is suitable for use as a temporary id or cookie name.
An even quicker and dirtier method is to simply convert a random double to a string:
String token = "token" + Math.random();
This is useful in test cases and one-offs, but I wouldn't put it into production code.
Comments
I do would apreciate it if you'd branch off a feed for stuff that's anything remotely python related, so the rest wouldn't clutter planetpython. But that's just my opinion, I'm sure many people like it a lot to read completely python unrelated stuff on planetpython.
I've been doing the following:
More verbose but the main differences are the length and the fact I create a Hex string.
I use this for cookies.
Florian, there's a python feed at:
http://cardboard.nu/feeds/blog_python.rdf.
Also, can you think of a concise way to do this in Python?
Here's a way to do any length (passed in):
Peace.
Hi
i need to know how to generate a random string with length 4 and characrters from A B C D E F ???thank uuuu
On Python, random string, length 4, from characters A,B,C,D,E and F.
probably there are shorter, smarter and more elegant ways.
Belto,
I still like my way better.
a
i need to know how to create a random string of names that does not duplicate any one name when randomized.
Since this is the #1 result for python random string in Google, it might be worth mentioning that Nasete's snippet can be condensed to:
Thats if every character should only be used once. If characters should be reused you could do it like this: