What happens when the CapsLock key on your keyboard doesn't have a notch in it?

"This hPPENS."

The goal of this program is to consistently emulate keyboard misses where each A press is replaced with CapsLock. Uppercase 'A's from the source should yield the same effect. When CapsLock is enabled, capitalization is reversed.

Test Cases

"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."

"Compilation finished successfully."

"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
-> "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"

"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."

-> "" (Without the notch, no one can hear you scream)

"CapsLock locks cAPSlOCK"

-> "wHt if CPSlOCK IS lreDY ON?"

The winning criterion is, as usual, the size of the submitted program's source code.

  • 107
    \$\begingroup\$ Welcome to the site! This is a nice first challenge, and unfortunately very relatable for me and my fT FINGERS. \$\endgroup\$ – DJMcMayhem Mar 14 '18 at 18:29
  • 5
    \$\begingroup\$ suggested test case : teSTateSTateSTateST \$\endgroup\$ – Rod Mar 14 '18 at 18:44
  • 82
    \$\begingroup\$ If only the enter key also had a notch in it so this wouldn' \$\endgroup\$ – 12Me21 Mar 14 '18 at 19:33
  • 68
    \$\begingroup\$ t happen....... \$\endgroup\$ – 12Me21 Mar 14 '18 at 19:33
  • 19
    \$\begingroup\$ Literally joined this site to upvote "Without the notch, no one can hear you scream" \$\endgroup\$ – lucasvw Mar 15 '18 at 21:10

56 Answers 56


MATL, 23 20 bytes

'a A'Yb&Ybt2L)Yo2L(g

Try it online!


'a A'Yb   % form a cell array containing {'a', 'A'}
&Yb       % split input into substrings, with either of those ('a' or 'A') as delimiters
t2L)      % extract out the even positioned cells from that result
Yo        % switch the case of those substrings
2L(       % place the result back in even positioned cells of the original cell array
g         % convert cell array to matrix, concatenating all substrings in the process
          % implicit output

Older answer (23 bytes):


Other methods I tried:


CJam, 31 bytes



Loops through searching for a and non-a

Try it online!

CJam, 47 bytes

Slightly more fun version


Try it online!


This code has two parts.

               Part 1
 q                          -> Read all input as a single string
 'a'Aer                     -> Replace 'a' in string with 'A'
 'A/                        -> Split by 'A' leaving empty sets
 _                          -> Duplicate
 2%                         -> Get all rows where i%2 is 0
 \                          -> Swap top two elements of stack
 2/                         -> Split into array with groups of length 2
 z                          -> Zip/Transpose
 )\;                        -> Right uncons, swap and pop.

               Part 2
  _[el_eu]                  -> Create an array containing the lower case and upper case version
  z                         -> Zip/Transpose
   \                        -> Swap top two
   (                        -> Uncons left
   @                        -> Rotate top three elements of stack
   |                        -> Set union
   1=                       -> Get element at array indice 1 (Wraps)
   \                        -> Swap top two
  }%                        -> Map onto every element of string
  e_                        -> Flatten
 }%                         -> Map onto every element of array
]z                          -> Zip/Transpose

The first part splits the string by 'A' leaving any empty sets behind. For the string "baacadE" that will give the following array.

["b", "", "c", "dE"]

That way, all normal case elements are at even indices and reverse case are odd. Which After executing the rest of the first part gives the following.

[["b", "c"], ["", "dE"]]

The second part will take the odd half and reverse the case of every string. This is done with the set union operator |. So for the element "dE" It will do the following. Since the set union operator preserves the order of the elements found in the first string/array we can always assume the reverse case element will be the second one in the string/array.

["dE", "dD"]
["dD", "dE"]
["dD", "E", "d"]
["E", "d", "dD"]
["E", "dD"]
["E", "D"]
["D", "E", "eE"]
["D", "Ee"]
["D", "e"]

All That is left to do is zip up the two halves.


Rust, 330 bytes

fn main(){let mut i=String::new();std::io::stdin().read_line(&mut i);let mut o=vec![];let mut c=false;for l in i.trim().as_bytes(){if*l==65||*l==97{c=!c;}else if c{if l.is_ascii_uppercase(){o.push((*l).to_ascii_lowercase());}else{o.push((*l).to_ascii_uppercase());}}else{o.push(*l);}}println!("{}",String::from_utf8(o).unwrap());}


fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input);
    let mut output_chars = vec![];
    let mut capslock = false;
    for letter in input.trim().as_bytes() {
        if *letter == 65 || *letter == 97 {
            capslock = !capslock;
        } else if capslock {
            if letter.is_ascii_uppercase() {
            } else {
        } else {
    println!("{}", String::from_utf8(output_chars).unwrap());

Since this uses bytes instead of chars in the loop, 65 and 97 are the byte values for 'A' and 'a'.

I'm new to Rust, so this might be golfable further.

  • 2
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Giuseppe Mar 15 '18 at 12:09

Python 3, 114, 101, 97 bytes

import re
print(''.join(i.swapcase()if j%2else i for j,i in enumerate(re.split('a|A',input()))))

Split on all a's and toggle the case on the odd parts

Thanks @ElPedro !

  • \$\begingroup\$ Can reduce to 96 by not assigning input() to the variable s. Try it online! \$\endgroup\$ – ElPedro Mar 15 '18 at 13:11
  • \$\begingroup\$ Good one @ElPedro I will edit! \$\endgroup\$ – Rick Rongen Mar 15 '18 at 13:13

Chip, 64 bytes


Try it online!

How it works

This is where I wish I could color-code the source. However, all of the below are full programs, and may be run on their own.

First things first, write a (slightly mangled) cat program.



Now invert capitalization of all characters A-Za-z.

This is determined by:

  1. c & 0x1F != 0
    • Filter out anything whose low 5 bits are zero
    • This is done by the left most column and upper ~
  2. ((c & 0x1F) + 0x5) & ~0x1F == 0
    • Filter out anything, that when added to 5, carries into or beyond the 6th bit
    • This is done by the two # columns
  3. c & 0x40 != 0
    • Filter out anything that is less than 64
    • This is done by the lower ~

The program assumes it will receive no characters above 127.

The results are aggregated and, the inversion is done by the { at the bottom.

>C#. Bb
>D## Cc
>E## Dd
`~+' Ee

But attach that to a toggle (T flip-flop) that is initially off. Now, the toggle decides whether to invert the capitalization, and the filter from above decides which characters to apply it to. Put a * above the m to toggle on every cycle.

>C#. Bb
>D## Cc
>E## Dd
`~+' Ee

Toggle the toggle when we see an Aa, and suppress that character too. We have an Aa if the filter above says we have A-Za-z, and the low five bits equal one (c & 0x1F == 1).


Javascript (ES6), 64 bytes


Let me know if you think this is broken :)

(edit: simplified ternary)

  • 1
    \$\begingroup\$ This doesn't seem to work with letters that are already uppercase. \$\endgroup\$ – Yair Rand Mar 25 '18 at 19:59

><>, 139 129 bytes

1vo   <
^o+< >::"aA"@=?^=?^$v
^o-^?  ("^"$*48:v?@:<
^ vv? )"Z":v?(< >>o
  >  ^v  < >:0 )?^;
  :< ^v?( "a"

A language with no concept of "characters" is surely the right tool for the job :)


x86-64, 31 bytes

Conforms to the System-V calling convention, tested in Ubuntu 16.04. Takes input from a pointer to a null-terminated in rsi, and outputs the result as a null-terminated string in rdi. rdi is expected to pointer to a buffer that's already been allocated with sufficient size.

Disassembly for byte count:

   0:       31 d2                   xor    edx,edx
   2:       ac                      lods   al,BYTE PTR ds:[rsi]
   3:       88 c1                   mov    cl,al
   5:       24 df                   and    al,0xdf
   7:       3c 41                   cmp    al,0x41
   9:       75 05                   jne    10 <not_A>
   b:       80 f2 20                xor    dl,0x20
   e:       eb f2                   jmp    2 <loop>
  10:       2c 41                   sub    al,0x41
  12:       3c 19                   cmp    al,0x19
  14:       77 02                   ja     18 <not_ascii>
  16:       30 d1                   xor    cl,dl
  18:       91                      xchg   ecx,eax
  19:       aa                      stos   BYTE PTR es:[rdi],al
  1a:       84 c0                   test   al,al
  1c:       75 e4                   jne    2 <loop>
  1e:       c3                      ret

Commented Assembly (GAS):

.intel_syntax noprefix
// rsi has the input char*, rdi has the output char*.
// Input char* is \0-terminated.
.global caps
    // Use this for xor mask.
    xor     edx, edx
// Loop is set up as a do-while loop.
    // al = *rdi++

    // Save the character we read into cl.
    // We use al because the instructions are shorter.
    mov     cl, al

    // Make upper case
    and     al, 0b11011111

    // 65 = 'A'
    cmp     al, 65
    jne     not_A
    // Invert capitialization mask
    xor     dl,0x20
    // Continue
    jmp     loop

    // Now we check if input character is ascii.
    // Basically, if (al-'A' > 'Z'-'A'), it's not ascii
    sub     al, 65
    cmp     al, 25

    ja      not_ascii
    // Flip capitilization if necessary.
    xor     cl, dl

    // Restore saved character that we read.
    // xchg is 1 byte, as opposed to mov, which is 2.
    xchg    ecx, eax

    // Write out the character to the output buffer.

    // If al == 0, break
    test    al, al
    jnz     loop

    // Just return, we've already written out the null
    // character to the output string.

Testing code in C, takes the input string via the first command line argument, prints out the result string:

#include <stdio.h> //puts
#include <stdlib.h> //malloc, free
#include <string.h> //strlen

void caps(char* output, char* input);

int main(int argc, char** argv) {
    char* instr = argv[1];
    char* buf = malloc(strlen(instr) + 1);
    caps(buf, instr);

    // Print converted string.


Pyth, 21 bytes


Try it here


           scR\AcQ\a   Split the input on 'a' and 'A'
          c         2  Split the blocks into pairs.
  m  d   d             For each pair...
   +P r2e              ... cAPSlOCK the second block.
ss                     Join the blocks together.

Pyth, 19 bytes


Try it here.

Saved one byte thanks to mnemonic.


Charcoal, 21 bytes


Try it online! Link is to verbose version of code. Explanation:


Loop through each character in the line of input.


Test whether it equals a in lower case.


If so then logically negate k. (Note that for some reason Charcoal considers k's default value None to be truthy.)


Otherwise check whether k is currently truthy.


If so then just print the character.


Otherwise check whether the current character is an upper case letter.


If it is then print it in lower case.


Otherwise print it in upper case.


Python 2, 103, 97 bytes

import re
def f(s):print"".join(j.swapcase()if i%2else j for i,j in enumerate(re.split('a|A',s)))

Python 3, 100 bytes

edit: save 3 bytes thanks to sonrad10! Thanks!

import re
print(''.join(map(lambda s:x.index(s)%2and s.swapcase()or s,x)))

Try it online!

To be further golfed (probably).

  • 1
    \$\begingroup\$ You could change from from re import * to import re and x=re.split(...) to save 3 bytes. \$\endgroup\$ – sonrad10 Mar 15 '18 at 11:25

APL (Dyalog Classic), 46 41 40 bytes


Try it online!


  • 'aA'~⍨ - Remove all a's from ...
  • ⊢819⌶⍨¨2|(⊢≠819⌶¨) - ... the alternating upper-and-lower-case of the argument ...
  • +≠\∘ ... based upon ...
  • (∨⌿'aA'∘.=⊢) ... the position of a and/or A.

Yabasic, 121 bytes

An anonymous function that takes input as a line of text from STDIN and outputs to STDOUT.

Line Input""s$
For i=1To Len(s$)
If u$="A"Then
ElsIf d Then?u$;Else?Lower$(c$);Fi

Try it online!




Test it here

Basically it decides to write in uppercase depending on a flag everytime it encounters an 'a'

  • 1
    \$\begingroup\$ Welcome to PPCG! It seems that your code assumes that the input is given in a hardcoded variable. However, all answers need to be either full programs or callable functions. Wrapping your code in a function which takes $str as a parameter would be the simplest fix, but I don't know if PHP has shorter ways to read the input from STDIN or a command-line argument instead. \$\endgroup\$ – Martin Ender Mar 16 '18 at 17:11

pwsh, 109 bytes

$Input|%{$i=$_[0]-ceq'a';$r='';foreach($s in $_.split('a')){$r+=($s.ToUpper(),$s.ToLower())[$i];$i=!$i};$r}

Python 3, 100 bytes

def f(x):x=x.replace('A','a').split('a');return''.join(i.swapcase()if i in x[1::2]else i for i in x)

Try it online!


Haskell, 96 94 Bytes

(Unix Line Endings)

import Data.Char
i c|c>'Z'=t c|0<1=toLower c
f(x:s)|t x=='A'=f$i<$>s|0<1=x:f s
f x=x
  • \$\begingroup\$ @Laikoni Unfortunate. I've fixed that now at the cost of 16 more bytes, but realised I was counting Windows line endings as 2 bytes, so I've clawed back 3 bytes by switching to Unix line endings. \$\endgroup\$ – Pharap Mar 19 '18 at 23:05

Haskell, ~~199~~ 133 bytes

import Data.Char
l c|isUpper c=toLower c|1<2=toUpper c
f _""=""
f b(c:cs)|toLower c=='a'=f(not b)cs|1<2=(if b then l else id)c:f b cs

Run using f False "<string>"

Ungolfed version:

import Data.Char

flipCase c
    | isUpper c = toLower c
    | otherwise = toUpper c

f "" _ = ""
f b (c:cs)
    | toLower c == 'a' = f cs $ not b
    | True = (if b then flipCase else id) c:f b cs
  • \$\begingroup\$ You can replace cs by a single letter variable name and define f as an infix function. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:06
  • \$\begingroup\$ Also note that when requiring extra arguments for the function, those need to be counted too. In this case the default would be to add 8 bytes to the byte count for f False and a newline. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:10
  • \$\begingroup\$ Instead of using a boolean it is shorter to use 0 and 1. not b then becomes 1-b, b in the conditional becomes b>0 and f False just f 0. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:14

Pip, 22 bytes

(The SC operator was added because of this challenge.)


Try it online!


                        i is 0, x is empty string (implicit)
                     q  Read a line of input
{                  }M   Map this function to its characters:
 LCa                     The character, lowercased
    Q'a                  Is it equal to lowercase a?
       ?                 If so:
          !:i             Logically negate i in place (0 -> 1, 1 -> 0)
        xX                Repeat the empty string that many times (thus, always return
                          empty string when the character is a/A)
             i?           Is i truthy (1)? If so, caps lock is on, so return:
               SCa         The character, swap-cased
                          Else return:
                  a        The character, unchanged

Excel VBA, 115 bytes

A declared subroutine that takes input, s of expected type variant/string and outputs to the range [A1].

Sub f(s)
For i=1To Len(s)
If u="A"Then d=Not d Else[A1]=[A1]+IIf(d,u,LCase(c))
End Sub

Java (OpenJDK 9), 90 bytes

int j=0;for(char t:c){if(t==65||t==97)j^=1;else System.out.printf("%c",j>0&&t>65?t^32:t);}

Try it online!

  • \$\begingroup\$ Welcome to PPCG! Submissions should be a program or function, and yours is currently a snippet. Adding c->{...} around your code mades it a valid lambda function. You can also golf || and && to | and &, and remove the {} around the for-loop. In addition, char can be int in this case. Try it online 90 bytes. Nice first answer, and enjoy your stay! Oh, and you might find Tips for golfing in Java interesting to read through. \$\endgroup\$ – Kevin Cruijssen Apr 9 '18 at 8:07

K4, 49 bytes




q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"The quick brown fox jumps over the lazy dog."
"The quick brown fox jumps over the lZY DOG."
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"Compilation finished successfully."
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
"WhT Hppens when the CPSLOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"


Fairly heavy, will look at other answers to see if I can golf this down:

{@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"} / the solution
{                                               } / lambda with implicit input x
                                           x,"a"  / append "a" to input
                                          _       / lowercase
                                      "a"=        / boolean list where input is "a"
                                     &            / indices where true
                                   w:             / save as w
                                  |               / reverse
                                _/                / drop over (remove these indices from...)
 @[ ;                 ;        ]                  / apply [var;indices;function]
                       .q.upper                   / uppercase
                  -':w                            / deltas of w
                 &                                / where, builds list of ascending values
                @                                 / apply
      .q.mod[;2]                                  / mod 2 to generate boolean list
   x                                              / apply uppercase to input x at these locations


Think I may have missed the point. I enabled/disable caps when an a is encountered. Passes the first test cases but not the ones where caps is apparently already enabled...


Lua, 152 151 bytes

p=io.read()a=0s=""for c in p:gmatch"."do l=c:lower()if c:find"[aA]"then a=(a+1)%2 else s=s..((c:find"%A"or a==0)and c or l==c and c:upper()or l)end end

Try it online!


p = io.read() -- reads the input
a = 0
s = ""
for c in p:gmatch"." do -- loops through the string 'p' (the input) calling each character 'c'
  l = c:lower() -- stores the lowercase version of 'c'
  if c:find("[aA]") then -- if 'c' is a lowercase or uppercase 'A'
    a = (a+1)%2 -- flip the value of 'a' between 0 and 1, from what I've seen it uses less space
    s = s..((c:find("%A") or a==0) and c or l==c and c:upper() or l)
    s = s..   -- append to the string 's'
            (c:find("%A") or a==0)   -- if this is not a letter or the "reversion" is off
                                   and c or   -- then append 'c' else
                                            l==c and c:upper() or l   -- if 'c' is lowercase then append it as uppercase else append it as lowercase

If you have any questions, feel free to ask and i'll try to answer.


Lua 5.3, 137 bytes

a=0s=""io.read():gsub(".",function(c)if c:find"[aA]"then a=not a else l=c:lower()s=s..(a and c or l==c and c:upper()or l)end end)print(s)

Try it online!


My result was very similar to @Visckmart above. But I included the print(s) in my byte count. Also the try it online test uses Lua 5.1, where my final result is in Lua 5.3. To make my final answer run on the website linked above I had to add a single space in between defining a and s: a=0 s="" which make it 138 bytes when using Lua 5.1


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.