Scala: Generating a sequence/list of all ASCII printable characters

I ran into a couple of interesting things today when trying to generate random alphanumeric strings in Scala, which can be summarized like this. I won’t get into the “random” stuff I was working on, but here are a couple of examples of how to generate lists of alphanumeric/ASCII characters in Scala:

scala> val chars = ('a' to 'Z').toList
chars: List[Char] = List()

scala> val chars = ('A' to 'z').toList
chars: List[Char] = 
List(A, B, C, D, E, F, G, H, I, J, K, L, 
     M, N, O, P, Q, R, S, T, U, V, W, X, 
     Y, Z, [, \, ], ^, _, `, a, b, c, d, 
     e, f, g, h, i, j, k, l, m, n, o, p, 
     q, r, s, t, u, v, w, x, y, z)

scala> val chars = (' ' to 'z').toList
chars: List[Char] = 
List( , !, ", #, $, %, &, ', (, ), *, +, 
     ,, -, ., /, 0, 1, 2, 3, 4, 5, 6, 7, 
     8, 9, :, ;, <, =, >, ?, @, A, B, C, 
     D, E, F, G, H, I, J, K, L, M, N, O, 
     P, Q, R, S, T, U, V, W, X, Y, Z, [, 
     \, ], ^, _, `, a, b, c, d, e, f, g, 
     h, i, j, k, l, m, n, o, p, q, r, s, 
     t, u, v, w, x, y, z)

The reason for why this appears to work the way it does is because of the order of ASCII characters, which you can see at asciitable.com. Here’s one last example that takes you from the first printable characters (a blank space) up to the last, which is the tilde (~) character:

scala> val chars = (' ' to '~').toList
chars: List[Char] = 
List( , !, ", #, $, %, &, ', (, ), *, +, 
,, -, ., /, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
:, ;, <, =, >, ?, @, A, B, C, D, E, F, G, 
H, I, J, K, L, M, N, O, P, Q, R, S, T, U, 
V, W, X, Y, Z, [, \, ], ^, _, `, a, b, c, 
d, e, f, g, h, i, j, k, l, m, n, o, p, q, 
r, s, t, u, v, w, x, y, z, {, |, }, ~)

If you ever need to easily generate a list of ASCII printable characters in Scala, I hope this is helpful.

A list of printable ASCII characters that are non-alphanumeric

While I’m in the neighborhood, here’s one way to create a list of all printable ASCII characters that are not numbers or letters:

val nonAlphaChars: List[Char] = (' ' to '/').toList ++:
    (':' to '@').toList ++:
    ('[' to '`').toList ++:
    ('{' to '~').toList

// result
nonAlphaChars: List[Char] = 
    List( , !, ", #, $, %, &, ', (, ), *, 
    +, ,, -, ., /, :, ;, <, =, >, ?, @, 
    [, \, ], ^, _, `, {, |, }, ~)

I can think of at least one other way to generate the same list of characters, but this is one possible approach.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.