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:
Random random = new Random(); long r1 = random.nextLong(); long r2 = random.nextLong(); String hash1 = Long.toHexString(r1); String hash2 = Long.toHexString(r2); String hash = hash1 + hash2;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):
String generate(int cch) { int cb = (cch + 3) / 4 * 3; // base 64: 3 bytes = 4 chars byte[] ab = new byte[cb]; m_rnd.nextBytes(ab); // session IDs should be random // encode the random bytes as a base-64 value of the desired length; // also: replace the special character '/' with the legal '$' return new String(Base64OutputStream.encode(ab), 0, cch).replace('/', '$'); }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.
import random string = ' ' for i in random.sample('ABCDEF',4): string+=iprobably there are shorter, smarter and more elegant ways.
package test; import java.util.Random; public class Ran { public static void main(String st[]){ String str=new String("QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"); StringBuffer sb=new StringBuffer(); Random r = new Random(); int te=0; for(int i=1;i<=4;i++){ te=r.nextInt(62); sb.append(str.charAt(te)); } System.out.print(sb.toString()); } }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:
import random string = ''.join(random.sample('ABCDEF', 4))Thats if every character should only be used once. If characters should be reused you could do it like this:
import random string = '' for i in range(4): string += random.choice('ABCDEF')''.join([random.choice('ABCDEF') for x in xrange(4)])