Generate a Sequence of Characters from 'A'-'Z'

Generate a sequence of characters from 'A'-'Z'

Use LETTERS and letters (for uppercase and lowercase respectively).

Create a sequence between two letters

This would be another base R option:

letters[(letters >= "b") & (letters <= "f")]
# [1] "b" "c" "d" "e" "f"

Generate character sequence from 'a' to 'z' in clojure

If code looks "verbose" it's often just a sign that you should factor it out into a separate function. As a bonus you get the chance to give the function a meaningful name.

Just do something like this and your code will be much more readable:

(defn char-range [start end]
(map char (range (int start) (inc (int end)))))

(char-range \a \f)
=> (\a \b \c \d \e \f)

Python: how to print range a-z?

>>> 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])]

Better way to generate array of all letters in the alphabet

I think that this ends up a little cleaner, you don't have to deal with the subtraction and indexing:

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

A to Z list of char from Enumerable.Range

Well, string is IEnumerable<char>, so this would also work:

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList()

You have to weigh the pros and cons on this.

Pros:

  • Easier to read the above code than your loop (subjective, this was my opinion)
  • Shorter code (but probably not enough to account for much)

Cons:

  • Harder to read if you don't know what .ToList() will do with a string
  • Can introduce bugs, for instance, would you easily spot the mistake here:

    "ABCDEFGHIJKLMN0PQRSTUVWXYZ".ToList()

    By easily I mean that you would spot the mistake as you're just reading past the code, not if you knew there was a problem here and went hunting for it.

Random string generation with upper case letters and digits

Answer in one line:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

or even shorter starting with Python 3.6 using random.choices():

''.join(random.choices(string.ascii_uppercase + string.digits, k=N))

A cryptographically more secure version: see this post

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

In details, with a clean function for further reuse:

>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'

How does it work ?

We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.

string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:

>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

Then we use a list comprehension to create a list of 'n' elements:

>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']

In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).

Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:

>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'

Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:

>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']

Then we just join them with an empty string so the sequence becomes a string:

>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'

Groovy: Generate random string from given character set

If you don't want to use apache commons, or aren't using Grails, an alternative is:

def generator = { String alphabet, int n ->
new Random().with {
(1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
}
}

generator( (('A'..'Z')+('0'..'9')).join(), 9 )

but again, you'll need to make your alphabet yourself... I don't know of anything which can parse a regular expression and extract out an alphabet of passing characters...

Generate random string/characters in JavaScript

I think this will work for you:

function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}

console.log(makeid(5));

Creating a random string with A-Z and 0-9 in Java

Here you can use my method for generating Random String

protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;

}

The above method from my bag using to generate a salt string for login purpose.



Related Topics



Leave a reply



Submit