g | x | w | all
Bytes Lang Time Link
012Haskell + hgl240223T174129ZWheat Wi
129Rust240509T083518Z138 Aspe
099YASEPL240223T183030Zmadeforl
048R240327T084704ZPatric
043Scala 3240227T084150Zt9dupuy
078Scala 3240310T130535Z138 Aspe
179Pascal240225T165456ZKai Burg
041Labyrinth240227T053314ZBubbler
055Rattle240227T024422ZDaniel H
056JavaScript ES6240222T190205ZArnauld
008Brachylog240226T142433ZFatalize
024K ngn/k240222T223848Zovs
011Bash240224T142456Zvengy
107Lua240225T112524ZEd The &
007Japt v2.0a0240223T220422ZShaggy
064Java 10240223T151133ZKevin Cr
071Excel240223T141838ZEngineer
016Bash + coreutils240223T140011Zqwr
042APL+WIN240223T090454ZGraham
002V vim240223T082935Ztsh
007MathGolf240223T082846ZKevin Cr
00105AB1E legacy / 2sable240223T082149ZKevin Cr
058Haskell240223T044422Ztotallyh
031R240223T071356Zpajonk
020K ngn/k240223T065533ZBubbler
012APL Dyalog APL240223T033154ZMukundan
014J240222T202814ZJonah
014Perl 5 p240222T223749ZXcali
142Go240222T223111Zbigyihsu
042PowerShell Core240222T210912ZJulian
009Japt v2.0a0240222T211209Znoodle p
141TypeScript’s type system240222T205318Znoodle p
010Charcoal240222T202809ZNeil
007Retina 0.8.2240222T202408ZNeil
040C gcc240222T191608ZMukundan
001Uiua SBCS240222T192013Zchunes
059Acc!!240222T184515ZDLosc
047Python 3240222T184058ZLarry Ba
012Python240222T182132ZMukundan
002MATL240222T183556ZLuis Men
001Vyxal 3240222T182232ZLarry Ba

Haskell + hgl, 16, 12 bytes

m$TL?.TU~<iU

Attempt This Online!

Thanks to Bubbler's comment on a different post for helping me realize how to take 4 bytes off

Explanation

This is really simple. m maps across a string iU checks if a character is uppercase, TU makes a character uppercase TL makes it lowercase.

Using parsers, 22 bytes

gk$my$(TL<pU)#|(TU<hd)

Attempt This Online!

Using regex, 38 bytes

skX$nt$ozW(:)(Β<>β)$K '{'<Fk"_|"<Alf

Attempt This Online!

This builds the regex

A{a_|B{b_|C{c_|D{d_|E{e_|F{f_|G{g_|H{h_|I{i_|J{j_|K{k_|L{l_|M{m_|N{n_|O{o_|P{p_|Q{q_|R{r_|S{s_|T{t_|U{u_|V{v_|W{w_|X{x_|Y{y_|Z{z_|a{A_|b{B_|c{C_|d{D_|e{E_|f{F_|g{G_|h{H_|i{I_|j{J_|k{K_|l{L_|m{M_|n{N_|o{O_|p{P_|q{Q_|r{R_|s{S_|t{T_|u{U_|v{V_|w{W_|x{X_|y{Y_|z{Z_

In hgl's regex flavor A{a_ matches an A but returns it as a. So this does this for every letter uppercase and lowercase.

Reflection

It's really weird that the main answer uses basically no function composition, and the only infix function it uses is function application, especially considering it uses 6 functions in total. However the l3 is still glue, and is clearly costing more than it should. I golfed away the l3 now, which is good.

The parser version is never going to be competitive for this challenge, but I did it anyway to get practice with that part of the library. 22 bytes is not awful, I don't think, but it could probably be improved.

Although the regex usually beats the parser when it is possible to write a regex, for this specific task the regex answer is even less likely to be competitive than the parser. It is fun to build the regex from components rather than

Rust, 129 bytes

129 bytes, it can be golfed more.


Golfed version. Attempt This Online!

|x:&str|->String{x.chars().map(|c|if c.is_uppercase(){c.to_lowercase().to_string()}else{c.to_uppercase().to_string()}).collect()}

Ungolfed version. Attempt This Online!

fn swapcase(input: &str) -> String {
    input
        .chars()
        .map(|c| {
            if c.is_uppercase() {
                c.to_lowercase().to_string()
            } else {
                c.to_uppercase().to_string()
            }
        })
        .collect()
}

fn main() {
    assert_eq!(swapcase("abc"), "ABC");
    assert_eq!(swapcase("ABC"), "abc");
    assert_eq!(swapcase("Mixed Case"), "mIXED cASE");
    assert_eq!(swapcase("1234"), "1234");
    assert_eq!(swapcase("123#$%hIjK456"), "123#$%HiJk456");
    println!("All tests passed.");
}

YASEPL, 99 bytes

=f=1'=l®1=i`1=s¥i,1=w$32=j$65=m$91`2!$j»}3,s,4!j+}2,m,2!)s!m}3,123,3+w!j+6!w-64|2`4$j+w»`3!~!i+}2,l

explanation:

=f=1'=l®1=i`1=s¥i,1=w$32=j$65=m$91`2!$j»}3,s,4!j+}2,m,2!)s!m}3,123,3+w!j+6!w-64|2`4$j+w»`3!~!i+}2,l         packed
=f                                                                                                          declare F (character that gets printed)
  =1'                                                                                                       get input from user, set result to var1
     =l®1                                                                                                   declare L (length of var1)
         =i                                                                                                 declare I (increment variable)
           `1                                                                               !i }2,l         while I < L ...
             =s¥i,1                                                                                           set S as var1[i]
                   =w$32                                                                                      set W as 32 (switcher)
                        =j$65                                                                                 set J as 65 (second increment variable)
                             =m$91                                                                            set M as 91 (max)
                                  `2          !j }2,m,2                                                       while J < M...
                                    !$j»                                                                        set F to char(J)
                                        }3,s,4                                   `4                             if F == S...
                                                                                   $j+w»                          break out of loop, set F to char(J+W)
                                                                                        `3!~                      print F, and continue
                                                +                                                               else, add 1 to j and loop.
                                                       !)s                                                    set F to S
                                                          !m}3,123,3                    `3                    if M == 123...
                                                                                          !~                    print F, and continue
                                                                    +w                                        else... / add W to M
                                                                      !j+6                                      add 6 to J
                                                                          !w-64                                 subtract 64 from W (making it negative)
                                                                               |2                               go back to point 2
                                                                                              +               once all done, add 1 to I and loop

R, 48 bytes

\(s)gsub("([A-Z]*)([a-z]*)","\\L\\1\\U\\2",s,,T)

(T for perl=TRUE)

Scala 3, 52 bytes 43 bytes

_.map(c=>if(c>'Z')c.toUpper else c.toLower)

Attempt This Online!

-5 bytes thanks to @movatica

-4 bytes thanks to @Bubbler

Scala 3, 78 bytes

78 bytes, it can be golfed more.

_.map{case c if c.isUpper=>c.toLower;case c if c.isLower=>c.toUpper;case c=>c}

Attempt This Online!

Pascal, 179 B

This is a full program requiring a processor supporting ISO standard 10206 “Extended Pascal” (in particular the index function). Furthermore the implementation must provide uppercase and lowercase characters.

program p(input,output);const
A='ABCDEFGHIJKLMNOPQRSTUVWXYZ';B='abcdefghijklmnopqrstuvwxyz';var
C:char;begin while not EOLn do begin
read(C);write((C+B+A)[index(A+B,C)+1])end end.

Ungolfed:

program swapCase(input, output);
    const
        modernLatinAlphabetMajuscule = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        modernLatinAlphabetMinuscule = 'abcdefghijklmnopqrstuvwxyz';
    var
        buffer: char;
    begin
        while not EOLn(input) do
        begin
            { This is equivalent to `buffer ≔ input↑; get(input)`. }
            read(input, buffer);
            { The `+` operater concatenates string and character values. }
            write(
                    output,
                    (
                        { If `index` (below) returns zero
                          (meaning pattern not found)
                          the value of `buffer` is used. }
                        buffer
                        + modernLatinAlphabetMinuscule
                        + modernLatinAlphabetMajuscule
                    )[
                        { The `index` function returns the index of
                          the pattern (second parameter)
                          in the sample (first parameter). }
                        index(
                              modernLatinAlphabetMajuscule
                            + modernLatinAlphabetMinuscule,
                            buffer
                        { In Pascal `string` indices are 1‑based. }
                        ) + 1
                    ]
                )
        end
    end.

Note, the program does not work correctly if input is empty since there is no EOF test.

Labyrinth, 41 bytes

" @
,::4/*_
. _6  "
$*  %23
326#(
_ /
%#)

Try it online!

Labyrinth doesn't have any built-ins related to letter case, and making multiple if-branches is incredibly wacky. Fortunately, it can be worked around using arithmetic operations. It also helps that it has the XOR operator, which means it suffices to identify letters vs. non-letters and apply XOR 32.

The code is kinda obfuscated by the use of "stack height" which saves 1 over pushing the first digit literally (_ push 0 and then append a digit). Unobfuscated, the code does the following:

Big loop:
  ,::    getchar(x), dup twice [x x x]
         exit (turn left) on EOF(-1), continue (turn right) otherwise(positive)
  _64/*  [x x2]  make chars 63 or below into 0 -> x2
  _32%   [x x3]  modulo 32 -> x3 (letter iff 1 <= x3 <= 26)
  (_26/  [x x4]  decrement and divide by 26 -> x4 (letter iff x4 == 0)
  )_2%   [x b]   increment and modulo 2 -> b (0 or 1, 1 means letter)
  _32*$  [x']    x XOR 32 if letter, x otherwise
  .      []      putchar

Rattle, 55 bytes

|!II^P[gnsF0*32+~,>]`:sF2$F1-~:s<91[1g>64]:s<123[1g>96]

Try it Online!

By design, Rattle does not have many built-ins to encourage more creative problem-solving. This means there is no built-in for checking or changing character case whatsoever. With the current number of bytes, this Rattle code is able to 1) iterate over all characters, 2) check if the character is upper-case or lower-case (implemented from scratch), and 3) swap the character case if this criteria is met.

This code is explained thoroughly because it's probable that a shorter solution exists (with the lack of built-ins for this in mind) - I encourage you to try to beat this code length!

Explanation

|                        get input
 !                       disable implicit output
  I                      split into chars
   I^                    get number of chars
     P                   reset pointer
      [...]`             loop N times, N = number of chars

g                        get the value at the pointer
 n                       convert to ASCII int
  s                      save to memory
   F0                    call local function 0 (returns -1, 0, or 1)
                           (-1 if a-z, 1 if A-Z, 0 otherwise)
     *32                 multiply by 32 (the difference between A-a, B-b, etc.)
        +~               add value in memory
          ,              output character corresponding to ASCII value
           >             move pointer right

:                        start local function 0
 s                       save input (passed implicitly) to memory
  F2                     call local function 2 (returns 1 if a-z, 0 otherwise)
    $                    swap result with value in memory
     F1                  call local function 1 (returns 1 if A-Z, 0 otherwise)
       -~                subtract value in memory (becomes -1 if a-z, 1 if A-Z, 0 otherwise)

:                        start local function 1 (checks if A-Z)
 s                       save input (passed implicitly) to memory
  <91                    check if the value is <91
     [1....]             if <91...
       g                 get the value in memory
        >64              check if the value is >64

:                        start local function 2 (checks if a-z)
 s                       save input (passed implicitly) to memory
  <123                   check if the value is <123
     [1....]             if <123...
       g                 get the value in memory
        >96              check if the value is >96

JavaScript (ES6), 56 bytes

-5 thanks to @ngn

s=>s.replace(/./g,c=>c[`to${c<{}?'Low':'Upp'}erCase`]())

Try it online!


JavaScript (Node.js), 45 bytes

-6 thanks to @ngn

s=>Buffer(s).map(c=>c^32*(c>>6&--c%32<26))+""

Try it online!

Brachylog, 8 bytes

{ụ?ḷ|ụ}ᵐ

Try it online!

Explanation

We check if a character is invariant by uppercasing, in which case we return the lowercase version, else we return the uppercase.

{     }ᵐ     Map for each character:
 ụ?            If the input uppercased is still the input
  ?ḷ           Output is the lowercased input
    |          Else
     ụ         Output is the uppercased input

K (ngn/k), 27 26 24 bytes

-1 byte thanks to @akamayu and another -1 thanks to @ngn!

ngn/K has a builtin for converting to lower case (_), but none for converting to uppercase, so there has to be some sort of codepoint arithmetic involved.

`c$32/|(0/2\1-"A[a{"')'\

Try it online!

Bash, 11 bytes

The ~~ operator in Bash can be used to toggle the case of all characters in a string.

echo ${1~~}

Try it online!

Lua, 107 bytes

o=""s=io.read()for c in s:gmatch"."do if c==c:lower()then o=o..c:upper()else o=o..c:lower()end end print(o)

Try it online!


Explanation

First time golfing with Lua, and also the first time I'm officially making a proper program with it 😇

We create two strings for our output and input.

o = ""
i = io.read()

Then we use a generator function that yields the matched group expression as the loop repeats (for lack of true understanding, this is what I can come up as a description). Using . ensures that gmatch returns individual characters.

for c in s:gmatch"." do
    -- ...
end

In the loop we do a test, if the character is lower-case already, we convert it to upper-case. Note that this test automatically lets uncased characters like punctuation and numbers to pass, since they stay the same.

After the conversion, we concatenate the character to the output string.

if c == c:lower() then
    o = o .. c:upper()
else
    o = o .. c:lower()
end

Then we print the output string

print(o)

--

Full un-golfed code

o = ""
s = io.read()

for c in s:gmatch"." do
    if c == c:lower() then
        o = o .. c:upper()
    else
        o = o .. c:lower()
    end
end

print(o)

Japt v2.0a0, 7 bytes

r\lÈc^H

Try it

Java 10, 64 bytes

s->{for(var c:s)System.out.print(c>64&c<91|c>96&c<123?c^=32:c);}

Input as a character-array; output is printed directly to STDOUT.

Try it online.

Explanation:

s->{                  // Method with character-array parameter and no return
  for(var c:s)        //  Loop over the characters of the input:
    System.out.print( //   Print:
      c>64&c<91|c>96&c<123?
                      //    If the character is a letter:
       c^=32          //     Invert its case by XOR-ing the codepoint by 32 (the `^=`
                      //     instead of `^` is so it'll remain a character instead of
                      //     becoming an integer)
      :               //    Else (it's not a letter):
       c);}           //     Print the character as is

Excel, 71 bytes

=LET(c,MID(A1,ROW(A:A),1),d,LOWER(c),CONCAT(IF(EXACT(c,d),UPPER(c),d)))

Input is in the cell A1. Output is wherever the formula is. I feel like there should be a shorter way to do this but Excel is limited in its case-switching functions.

The LET() function allows you to define variable as a name,value pair. This saves us bytes by letting us reference data by a shorter name.

Screenshot

Bash + coreutils, 16 bytes

Exactly what tr is for.

tr A-Za-z a-zA-Z

Attempt This Online!

APL+WIN, 42 bytes

Prompts for input. Code adjusted to account for difference between APL+WIN atomic vector and that of Dyalog Classic

⎕av[m+∊+/48 ¯48×(⊂m←⎕av⍳⎕)∊¨(⊂⍳26)+¨17 65]

Try it online! Thanks to Dyalog Classic

V (vim), 2 bytes

V~

Try it online!

MathGolf, 7 bytes

ô∙!=¿δ!

Try it online.

Explanation:

ô       # Loop over the characters of the (implicit) input-string,
        # using the following 6 characters as inner code-block:
 ∙      #  Triplicate the current character
  !     #  Lowercase the top copy
   =    #  Pop the top two, and check whether they're still equal
    ¿   #  If they were equal (aka the character was lowercase, or not a letter):
     δ  #   Uppercase the character
    ¿   #  Else (it was an uppercase character)
     !  #   Lowercase the character instead
        # (after the loop, the entire stack is joined together and output implicitly)

05AB1E (legacy) / 2sable, 1 byte

š

Try it online in 05AB1E (legacy) or try it online in 2sable.

05AB1E, 2 bytes

Try it online.

Explanation:

Builtin to switch the case of all ASCII letters in the (implicit) input-string, after which the result is output implicitly.

Haskell, 64 58 bytes

-6 bytes thanks to Bubbler.

import Data.Char
f s=[last(toUpper:[toLower|c<'a'])c|c<-s]

Try it online!

I wish there were a more interesting solution but it probably looks like:

85 bytes

f s=[last$c:[toEnum$o-(signum$o-91)*32|64<o&&o<91||96<o&&o<123]|c<-s,o<-[fromEnum c]]

Try it online!

...Yeah. Gross. There's also:

98 bytes

f s=[last$c:[n|(Just n)<-[m]]|c<-s,m<-[lookup c$zip['a'..'z']['A'..'Z']++zip['A'..'Z']['a'..'z']]]

Try it online!

I feel like this could get a whole lot better but I'm blanking.

R, 31 bytes

\(s)chartr("a-zA-Z","A-Za-z",s)

Attempt This Online!

K (ngn/k), 20 bytes

{`c$(_x)-32*~"a{"'x}

Try it online!

Lowercase the entire string using the builtin _ and then subtract 32 from those that were already lowercase to make them uppercase.

{`c$(_x)-32*~"a{"'x}    x: string
             "a{"'x     for each char c in x, -1 if c<'a', 0 if 'a'<=c<'{',
                        1 if '{'<=c
         32*~           boolean not times 32; gives 32 for lowercase in input
    (_x)                lowercase version of x
        -               subtract to uppercase the lowercase
 `c$                    convert the result of arithmetic back to char type

APL (Dyalog APL), 13 12 bytes

⊢⎕C¨⍨¯1*⎕C≠⊢

Attempt This Online!

⊢⎕C¨⍨¯1*⎕C≠⊢­⁡​‎‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌­
           ⊢  # ‎⁡input
          ≠   # ‎⁢not equal to (vectorized)
        ⎕C    # ‎⁣lowercase version
     ¯1*      # ‎⁤-1 ^ x (convert 0 to 1, 1 to -1)
 ⎕C¨⍨         # ‎⁢⁡convert to uppercase where 1 and lowercase where -1
⊢             # ‎⁢⁢on input
💎

Created with the help of Luminespire.

APL (Dyalog Extended), 1 byte

-

Try it online!

J, 16 14 bytes

3!:12"+~'`'&I.

NOTE: fails on ATO's older J but works in j9.4.2

-9 thanks to ovs!!

-2 thanks to Bubbler for a very nice refinement!

The basic clever idea is due to ovs. The idea to simplify it using "insert before" to get the upper/lower flags '`'&I. is due to Bubbler.

J, 24 bytes

g`tolower@.(=g=.toupper)

Attempt This Online!

-1 thanks to ovs for this variant using agenda!

This showcases an interesting fact about agenda, which is that if you provide it a list of integers, it runs on each on separately, returning a list of results.

So it applies 'tolower' to every uppercase letter, and toupper to every lowercase one.

J, 27 25 bytes (original)

(=0{g)`(g=.3!:12"{~&0 1)}

Attempt This Online! (NOTE: fails on ATO's older J but works in j9.4.2)

29 byte variant that works on ATO:

(=0{g)`(g=.tolower,:toupper)}

The variant is clearer for the explanation anyway:

Perl 5 -p, 14 bytes

s/\pL/$&^$"/ge

Try it online!

Go, 142 bytes

import(q"strings";."unicode")
func f(s string)string{return q.Map(func(r rune)rune{if IsUpper(r){r=ToLower(r)}else{r=ToUpper(r)};return r},s)}

Attempt This Online!

One of the few times Go provides a Map function, and it's on strings.

PowerShell Core, 42 bytes

$args|%{[char]($_-bxor32*($_-in"a".."z"))}

Try it online!

Takes an array of characters as input
Returns an array of characters

Japt v2.0a0, 9 bytes

®c^H*Zè\l

Try it

®c^H*Zè\l­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­
®          # ‎⁡Map each character Z to:
 c         # ‎⁢  It transformed by passing its charcode through:
  ^        # ‎⁣    XOR with
   H       # ‎⁤      32
    *      # ‎⁢⁡      Multiplied by
     Zè    # ‎⁢⁢      Number of matches of the following regex in Z:
       \l  # ‎⁢⁣        [A-Za-z] (alphabetical)
💎

Explanation created with the help of Luminespire.

TypeScript’s type system, 141 bytes

141 bytes with capitalization builtins:

type G<C,U=Uppercase<C>,L=Lowercase<C>>=U extends L?C:C extends U?L:U
type F<S,O>=S extends`${infer C}${infer S}`?F<S,`${O&string}${G<C>}`>:O

186 bytes no builtins:

type F<S,O>=S extends`${infer C}${infer S}`?F<S,`${O&string}${"aAabBbcCcdDdeEefFfgGghHhiIijJjkKklLlmMmnNnoOopPpqQqrRrsSstTtuUuvVvwWwxXxyYyzZz"extends`${any}${C}${infer c}${any}`?c:C}`>:O

Charcoal, 10 bytes

⭆S⎇№αι↧ι↥ι

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

 S          Input string
⭆           Map over characters and join
    α       Predefined variable uppercase ASCII
   №        Contains
     ι      Current character
  ⎇         If true then
        ι    Current character
       ↧     Lowercased
          ι  Else current character
         ↥   Uppercased
             Implicitly print

Retina 0.8.2, 7 bytes

T`Ll`lL

Try it online! Link includes test cases. Explanation: Simply transliterates using the shortcuts for upper and lowercase letter ranges.

C (gcc), 40 bytes

f(char*s){if(*s^=isalpha(*s)/32)f(s+1);}

Try it online!

C (gcc), 45 42 bytes

f(char*s){if(*s^=isalpha(*s)?32:0)f(s+1);}

Try it online!

Uiua SBCS, 1 byte

¯

Try it on Uiua pad!

Acc!!, 59 bytes

N
Count i while _ {
Write _+_/65*(90/_-_/97*(122/_))*32
N
}

Try it online!

Explanation

Here's a slightly de-obfuscated version:

N
Count i while _ {
  Write _ + (_/65)*(90/_)*32 - (_/97)*(122/_)*32
  N
}

N reads a character of input and stores its ASCII code in the accumulator.

Count i while _ loops while the accumulator's value is nonzero. After the end of input (including an implicit trailing newline), N returns zero, so this loops over the entire input and then halts.

Acc!! doesn't have comparison operators, so we use integer division to determine what range a character code is in:

_/65 90/_ _/97 122/_ Range
0 >= 1 0 >= 1 _ < A
1 1 0 1 A ≤ _ ≤ Z
1 0 0 1 Z < _ < a
1 0 1 1 a ≤ _ ≤ z
1 0 1 0 z < _

Multiplying the first two tells us the character is uppercase, in which case we add 32 to make it lowercase. Multiplying the second two tells us the character is lowercase, in which case we subtract 32 to make it uppercase. We then Write out the modified character and read another one with N.

For the golfed version, we pull the common factor of 32 out of both products, and then observe that _/65 can only ever be 0 or 1, and it's only 0 when we don't want to modify the character, so it can be pulled out as well.

Python 3, 47 bytes

lambda s:[chr(ord(c)^32*c.isalpha())for c in s]

Try it online!

Python, 12 bytes

str.swapcase

Attempt This Online! (Python 3)
Attempt This Online! (Python 2)

Pyth, 3 bytes

rQ2

Attempt This Online!

 Q    # input
r 2   # swapcase

MATL, 2 bytes

Yo

Try it at MATL online!

Vyxal 3, 1 byte

N

Try it Online!