# Output the alphabet, the ALPHABET, or just a character

The challenge is simple:

Write a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either.

Rules:

• The input can be function argument or from STDIN
• The input will be any of the printable ASCII characters from 32 to 126 (space to tilde).
• The input may be inside quotation marks,'x' or "x", but remember that ' and " are valid input and should be supported.
• The input can be any of the letters in the alphabet, i.e. you can't assume it will be a or A.
• The output should be only one of the alphabets or the single symbol, but trailing newlines are OK.
• The letters in the alphabet should not be separated by spaces, commas or anything else.

Some examples:

F
ABCDEFGHIJKLMNOPQRSTUVWXYZ

z
abcdefghijklmnopqrstuvwxyz

"
"

<- Input:  Space
<- Output: Space


Shortest code in bytes win.

Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others.

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

## Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes


If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes


You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes


var QUESTION_ID=67357,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• Are we allowed to import packages like, in Python for example: import Random and then use Random.randint (obviously not for this challenge but still)? Dec 22 '15 at 15:28
• Yes, you may import packages. but the bytes for writing for instance import string are counted, thus it's often better to do workarounds. Note that the package must exist before the challenge is posted. Many challenges have something like: "Using packages that does this is not allowed", but that is not the case in this challenge. Dec 22 '15 at 15:36
• I'm assuming that by "quotes are valid input and must be supported" you mean that if your input method requires quotes then quotes as input would be escaped Dec 23 '15 at 5:10
• May we assume a REPL environment?
– cat
Dec 23 '15 at 17:38

# TeaScript, 5 bytes

xN(0)


TeaScript has a (almost) built-in for this :D

Try it online (note: the online interpreter has been updated to TeaScript v3 so in which this is N0)

Try all the test cases

### TeaScript 3, 2 bytes [non-competing]

Using TeaScript 3, this can become 2-bytes. This is non-competing because TeaScript 3 was made after this challenge

N0


### 1 byte alternative

If we could output 0123456789 for digits, then this could be:

°

• TeaScript 3 is valid. So, you may use it! Nov 2 '17 at 13:06

# Pyth, 10 bytes

h/#z[GrG1z


Test suite

We start by constructing a list with 3 elements: the lowercase alphabet, the uppercase alphabet, and the input. ([GrG1z) Then, we filter this list on the number of appearances of the input in the elements being nonzero. (/#z) Finally, we take the first element of the filtered list.

• Seriously, is there anything you couldn't solve with a few bytes of Pyth? I really need to learn this language.. Dec 22 '15 at 17:49
• Learn which language?...you mentioned two by name. :P Dec 22 '15 at 18:21
• @quintopia Well, why not both? :) Dec 22 '15 at 21:16
• Holy cow, this is clever! I just went with the obvious solution of ternary statements, which ended up being 14 bytes ?}zGG?}zKrG1Kz Dec 2 '19 at 21:28

# LabVIEW, 23 LabVIEW Primitives

The selector (the ? on the cse structure) is connected to a vi that is called Lexical Class. It ouputs numbers from 1-6 depending on input, 5 is lower case 4 is upper case.

The for loop goes 26 times to create an alphabet or once to pass the symbol through.

• As someone who had the (privilege? misfortune? you decide) of working in LabVIEW many years ago, your answers bring a smile to my day. =) Dec 22 '15 at 16:26

f c=filter(elem c)[['a'..'z'],['A'..'Z'],[c]]!!0


Usage example:

*Main> f 'g'
"abcdefghijklmnopqrstuvwxyz"
*Main> f 'H'
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
*Main> f '\''
"'"


Take all lists of ['a'..'z'], ['A'..'Z'] and the singleton list with the input char c where c is element of. For letters we have always two matches, so we pick the first one.

# JavaScript (ES6), 79 bytes

x=>(a="abcdefghijklmnopqrstuvwxyz",x>""&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)


## Explanation

JavaScript compares the code of each character alphabetically when comparing strings, so the codes of the characters used in the comparisons are 1 below and above the required range of characters.

x=>(
a="abcdefghijklmnopqrstuvwxyz", // a = lower-case alphabet
x>""&x<"{"?a:                  // if x is a lower-case letter, output alphabet
x>"@"&x<"["?a.toUpperCase():    // if x is an upper-case letter, output upper-case
x                               // else just output x
)


## Test

var solution = x=>(a="abcdefghijklmnopqrstuvwxyz",x>""&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)
X = <input type="text" oninput="result.textContent=solution(this.value)" />
<pre id="result"></pre>

• Is that actually the shortest way to produce a string with the entire alphabet in Javascript? If you wanted the entire printable ASCII-range, would you have to type every single character? Dec 22 '15 at 8:54
• @StewieGriffin Sadly it is. The only other way would be something like: for(a="",i=64;++i<91;)a+=String.fromCharCode(i). String.fromCharCode is very unsuitable for golfing, but sometimes it's the only way! Dec 22 '15 at 8:56
• In this case the balance is between String.fromCharCode and .toUpperCase (Dumb and Dumber) but toUpperCase is the winner Dec 22 '15 at 9:27
• Nice! I've tried a few different ways of golfing this further, but haven't found one that works. x=>x.replace(/[A-Z]/i,c=>c>""?a:a.toUpperCase(),a="abcdefghijklmnopqrstuvwxyz") does, but is one byte longer. Changing [A-Z] to \w works for everything except _. Your solution seems to be the shortest possible. Dec 22 '15 at 18:51
• Here's one of the shortests way to generate ABC...abc...? without a real for loop: (some padding) [for(_ of[...Array(i=64)])if(i++%32<26)String.fromCharCode(i)].join+x Dec 22 '15 at 19:34

## R, 90 75 bytes

a=scan(,'');l=letters;L=LETTERS;cat("if"(a%in%l,l,"if"(a%in%L,L,a)),sep="")


Thanks to Giuseppe.

Old version (90 bytes):

a=scan(,'');l=letters;L=LETTERS;if(a%in%l)cat(l,sep="")else if(a%in%L)cat(L,sep="")else a


Looks ugly, but those cats cannot be outsourced to functions, IMHO.

• 75 bytes Nov 9 '17 at 22:04
• 73 bytes: the 2nd parameter of scan can be any object of type character, so you can letters instead of ''. Sep 7 '19 at 17:34
• Can you replace the last sep="" with just the ""? Apr 29 at 4:46

# Python 3, 928482 74 bytes

Current version: 74, thanks to isaacg and wnnmaw!

lambda c:(c,''.join(chr(x+(67,97)[c>'Z'])for x in range(25)))[c.isalpha()]


Ungolfed: (for some definition of ungolfed

lambda c:
(
c,
''.join([chr(x + (67,97)[c > 'Z']) for x in range(25)])
)
[c.isalpha()]


First version: 92

def f(c):print(''.join([chr(x+(97if c>'Z'else 65)) for x in range(25)])if c.isalpha()else c)


Second version: 82, thanks to isaacg! :)

lambda c:''.join(chr(x+(97if c>'Z'else 65))for x in range(25))if c.isalpha()else c

• Hi, and welcome to PPCG! Nice answer. Here's a golfing suggestion: You can use a lambda expression (lambda c:) instead of an explicit definition (def f(c):print(), and save some bytes. Also, you don't need the space before the for. Dec 22 '15 at 11:09
• Ah, I assumed "output" to mean print, and not just return :) Neat, if that's the case it's down to 84, lambda c:''.join([chr(x+(97if c>'Z'else 65))for x in range(25)])if c.isalpha()else c. Thanks! Dec 22 '15 at 11:20
• Yeah, the standard definition of output on the site allow returning from functions, so you can edit the new version into your answer. Another golf is that the brackets aren't necessary - the function works exactly the same without them, as a generator comprehension instead of a list comprehension. Dec 22 '15 at 11:23
• Ah, haven't actually used generator comprehensions before, learning new things! Thanks again :) Dec 22 '15 at 11:27
• Note that when inputing " to the function, you need \" instead. Dec 22 '15 at 16:50

# Python 3, 1181059897 83 bytes

Simple solution. EDIT: Golfed with thanks to Erik the Golfer's suggestion.

lambda s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ':(s,(a,a.lower())[s.islower()])[s.isalpha()]


Ungolfed:

def f(s):
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if s.isalpha():
if s.islower():return a.lower()
else:return a
return s

• Could you use a ternary operator to save a few bytes? Something like return a.lower() if s.islower() else a. Dec 22 '15 at 13:00
• @DavidRobertson I'm not sure if you're reading my solution, which is the top line of code, correctly, but that is exactly what I'm doing. Dec 22 '15 at 13:57
• Ah! I was reading the ungolfed version. Sorry about that! Dec 22 '15 at 14:40
• @DavidRobertson Not a problem Dec 22 '15 at 15:21
• Golfed: lambda s,a='abcdefghijklmnopqrstuvwxyz':(s,(a,a.upper())[s.isupper()])[s.isalpha()] Jul 22 '16 at 10:04

# PHP, 62 7682 bytes

PHP is doing OK now:

<?=ctype_alpha($x=$argv[1])?join(range(Z<$x?a:A,Z<$x?z:Z)):$x;  Takes an input from command line, like: $ php alphabet.php A
$php alphabet.php "a"$ php alphabet.php " "
$php alphabet.php _  Edits • Saved 6 bytes by replacing 91>ord($x) with Z<$x. Thought way to complicated. Thanks to manatwork. • Saved 14 bytes by removing strtoupper and building the demanded range directly. • That ord() looks bad there. Try Z<$x?$a:strtoupper($a). Dec 22 '15 at 12:23
• @manatwork Haha, I've thought way to complicated in that second part. Thanks to point it out. Dec 22 '15 at 19:13
• Try ' '&$x^A to make uppercase and lowercase a and z. That is, your code becomes <?=ctype_alpha($x=$argv[1])?join(range(' '&$x^A,' '&$x^Z)):$x; Dec 23 '15 at 23:33
• @IsmaelMiguel This will have the exact same byte count. Dec 23 '15 at 23:50
• Don't worry - and it's still a nice way to obfuscate. ;) Dec 24 '15 at 0:01

# Perl, 4634 33 bytes

includes +2 for -nE

say/[a-z]/?a..z:/[A-Z]/?A..Z:$_  Run as perl -nE 'say/[a-z]/?a..z:/[A-Z]/?A..Z:$_'


• update 34 save 12 bytes by omitting for and using barewords, thanks to @Dom Hastings.
• update 33 save 1 byte using -E and say instead of print.
• @DomHastings Thanks! Should have known barewords were allowed there - and I should've seen that for :-/. Tried a bunch of approaches, (-p with $"='';$_="@_", even $a='/[a-z]/?a..z:';print eval$a.uc$a.'$_' but everything is longer... Dec 22 '15 at 21:51
• Had a think on this, if you set $_= instead of printing and use the -p flag instead of -n you can save another two... I still can't think of any other ways to save more so far... Dec 23 '15 at 11:04 • @DomHastings I tried that, but I can't set $_ to a list (that I know of). It would have to be interpolated ($_="@_") but that uses space as a separator so I'd have to do $"='' as well, (or use a join'',) which makes it longer. Not much wiggle room on this one! Dec 23 '15 at 15:07
• Hah, of course! You even said that (when I re-read the comment after not being at the pub...) I'll keep thinking on it, but you might be the shortest you'll get without using say instead of print! Dec 23 '15 at 15:28

# Ruby, 41 + 1 = 42

With switch -p, run

([*?A..?z]*'').scan(/\w+/){$&[$_]&&$_=$&}


This generates the string

ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz


and checks each contiguous block of "word characters", which happen to be just the lowercase and uppercase alphabets and the underscore character. If there were multiple consecutive word characters between Z and a, this trick wouldn't work.

Edited to add explanation, by request:

The -p flag does essentially

while( $_ = STDIN.gets ) #execute code print$_
end


[*?A..?z] is the array of characters between uppercase A and lowercase Z, in ASCII order. That's the uppercase alphabet, some non-letter characters, and the lowercase alphabet. *'' joins the array into a string, so we can call .scan on it. scan will find each match of the regular expression /\w+/, populate the magic variable $& with it, and call the block. Each time the block is iterated, it checks whether the matched string contains $_ and sets the output to that string if so. So if $_ is contained in either the uppercase or lowercase alphabet, it gets modified accordingly, otherwise it's unchanged. The ungolfed version would look something like while ($_ = STDIN.gets )
%w[ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz].each do |alphabet|
$_ = alphabet if alphabet.include?($_)
end
print $_ end  • Can you post an un-golfed version? I'm still not understanding fully how this works. Dec 24 '15 at 21:58 • Sure, posted one. Dec 26 '15 at 2:15 # CJam, 18 bytes '[,65>_elr:R]{R&}=  '[,65> pushes the uppercase alphabet, _el the lowercase alphabet, and r:R a single-char string that is read from STDIN and assigned to variable R. These are wrapped in an array (]) and the first one that has any chars in common with R is selected using {R&}=. • I'm trying to understand how to CJam, but I'm lost between the official doc and what I'm reading here. Can someone give me for example a page where I can understand why is _el the lowercase alphabet? Dec 23 '15 at 18:30 • Ah, el means "convert to lowercase". I've just pushed the uppercase alphabet, so now I duplicate it with _, then call el on the resulting copy. – Lynn Dec 23 '15 at 18:31 • I made a nice pdf containing (almost) all CJam commands. – Lynn Dec 23 '15 at 18:31 # Retina, 62 bytes [a-z] abcdefghijklmnopqrstuvwxyz [A-Z] ABCDEFGHIJKLMNOPQRSTUVWXYZ  The two short lines are the regex to match. If the input is lowercase (in the range [a-z]), it replaces that character (in this case, that is the entire input) with the lowercase alphabet. The process is similar for uppercase. If it's not a letter, no replacements are made, and it is outputted untouched. Try it online. ## Python 2.7.10, 9593 79 bytes This is my first time even attempting to golf, so please, any help or advice is extremely appreciated! from string import* lambda i:(i,(uppercase,lowercase)[i.islower()])[i.isalpha()]  Thanks to Morgan Thrapp for the help! • @MorganThrapp, that doesn't seem to work. Are you sure that it works in Python 2.7.10? Dec 22 '15 at 21:23 • It works in 2.7.8. What doesn't work? Dec 22 '15 at 21:24 • @MorganThrapp, actually, could you please explain first exactly how that works? Maybe it's just that I don't understand so I'm doing something wrong. Dec 22 '15 at 21:27 • Sure, it uses the fact that False == 0 and True == 1 to index into tuples. So, it first checks if it's a letter with isalpha, if it is, it returns 1 and then checks if it's lowercase and does the same. Dec 22 '15 at 21:28 • No problem! I love golfing, so I'm always happy to help out someone new! Dec 22 '15 at 21:31 # Ruby, 46 43 characters (42 characters code + 1 character command line option) [?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}  Thanks to: • Jordan for the === magic (-3 characters) Sample run: bash-4.3$ echo -n 'm' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
abcdefghijklmnopqrstuvwxyz

bash-4.3$echo -n 'W' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}' ABCDEFGHIJKLMNOPQRSTUVWXYZ bash-4.3$ echo -n '@' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
@


# MATL, 22 bytes

jtt1Y2XIm~Iw?km?Ik]]1$ This uses the current version (3.1.0) of the language. EDIT (Sep 15, 2017): Try it at MATL Online! (with a newer version of the language). ### Examples >> matl jtt1Y2XIm~Iw?km?Ik]]1$
> e
abcdefghijklmnopqrstuvwxyz

>> matl jtt1Y2XIm~Iw?km?Ik]]1$> T ABCDEFGHIJKLMNOPQRSTUVWXYZ >> matl jtt1Y2XIm~Iw?km?Ik]]1$
> "
"


### Explanation

j              % input string (assumed to be a single character)
tt             % duplicate twice
1Y2            % predefined literal: uppercase letters
XI             % copy to clipboard I
m~             % check if not member
I              % paste from clipboard I
w              % swap elements in stack
?              % if
k          % convert string to lowercase
m          % check if member
?          % if
I      % paste from clipboard I
k      % convert string to lowercase
]          % end
]              % end
1$% input specification for implicit printing  ## Perl, 23 bytes Includes +2 for -nE (instead of the normal +1) to be fair to the other perl solution Run with the input on STDIN without trailing newline: echo -n g | perl -lnE 'say/\pL/?a&$_|A..Z:$_'  Just the code: say/\pL/?a&$_|A..Z:$_  • Nice use of the fact that input is limited to 7-bit characters. Sep 28 '16 at 18:21 # Lua, 98 97 bytes Sadly, I didn't find a solution shorter than 26 bytes to set a with the alphabet. In fact, I didn't find shorter than 32. Edit : save 1 Byte thanks to @ATaco, was doing this error a lot when started with Lua :p c=io.read()a="abcdefghijklmnopqrstuvwyz"print(not c:find"%a"and c or c:find"%u"and a:upper()or a)  You can test it online on the official site or on ideone. If you use the former, the input won't work (disabled), so use the following source, where it is wrapped into a function. function f(c) a="abcdefghijklmnopqrstuvwyz" print(not c:find"%a"and c or c:find"%u"and a:upper()or a) end print(f("\"")) print(f("a")) print(f("Q"))  • You are not the only who not found shorter way to generate the alphabet in Lua. :( Dec 22 '15 at 11:29 • @manatwork haha, exactly the same thing, except I didn't have to print it, but to concatenate it ^^. At least, that mean there isn't a hidden trick I didn't know to do it ^^'. Dec 22 '15 at 13:44 • You can save a byte with c=io.read()a="abcdefghijklmnopqrstuvwyz" instead of a,c=... Sep 29 '16 at 0:13 ## Mathematica, 75 bytes #/.Thread[Join[a=Alphabet[],b=ToUpperCase@a]->Array[""<>If[#>26,b,a]&,52]]&  Pretty good score for a non-golfing language... Any solutions using character code processing would take more bytes, due to the costs of ToCharacterCode and FromCharacterCode. # C (function), 71 bytes f(s,n,c){n=1;if(isalpha(s))s-=s%32-1,n=26;for(c=s;c<s+n;)putchar(c++);}  • f(s,n,c){for(c=s-=(n=isalpha(s)?26:1)>1?s%32-1:0;c<s+n;)putchar(c++);} saves a byte. Dec 23 '15 at 17:41 • f(s,n){for(n=isalpha(s)?s-=s%32-1,s+26:s+1;s<n;)putchar(s++);} for 62 bytes Nov 11 '17 at 9:41 # Python, 81 bytes f=lambda z,a="abcdefghijklmnopqrstuvwxyz":[k for k in[a,a.upper(),z]if z in k][0]  This is basically a translation of the Pyth answer. It defines a function f that takes as argument the character and returns the result. • You mean if z in k, right? Also, f= is optional by default. – xnor Dec 22 '15 at 21:00 • @xnor Yes. Apparently I missed a Ctrl-C. Dec 22 '15 at 21:01 • Remove f=, make the function anonymous. -2 Jul 22 '16 at 10:13 # Jolf, 17 bytes Try it here. ? hpLipl? hpUipui ? if hpL the lowercase alphabet (array) contains i the input pl return the lowercase alphabet (string) ? else if hpU the uppercase alphabet (array) contains i the input pu return the uppercase alphabet (string) i otherwise, return the input implicit: print the result  ## Java, 165 characters class A {public static void main(String[]p){int c=p[0].charAt(0),d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);for(;e<f;e++){System.out.print((char)e);}}}  Generates the required output to stdout (rather than returning it). Input is via the runtime arguments. How it works. 1) Setup some integer variables c = the ASCII value of the first character of the first parameter of the runtime arguments. d = c converted to lowercase ASCII value (by ORing it with 32) b = calculation to see if d is a letter. Will be <0 if a letter. e = The start character for output. If ASCII value in d is a letter (see b) then it is set to 'A' (or 'a' by adding c AND 32 to 'A' ASCII value) else it is set to the original value of c. f = the number of characters to output. If it not a letter (see b) then this is set to 1 else it is set to 26 2) Loop from e to e+f outputing each character to stdout. • You know that for most challenges the solution can be provided either as complete program or a function? Given the enormous amount of boilerplate code in Java, a function may be shorter. Dec 23 '15 at 13:35 • Applying a couple of small tricks, without changing the logic, I got this: void f(char c){for(int d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);e<f;)System.out.print((char)e++);}. Dec 23 '15 at 15:29 ## MATLAB: 71 68 bytes i=input('');b=i<65|i>122|(i>90&i<97);[i*b,~b*((65:90)+32*(i>96)),'']  (thanks to OP for saving 3 bytes) Test: i='a' ans= abcdefghijklmnopqrstuvwxyz i='A' ans= ABCDEFGHIJKLMNOPQRSTUVWXYZ i='~' ans= ~  Explanation: Uppercase alphabet occupies 65:90 ASCII characters. Lowercase alphabet is at 97:122 ASCII. So, b=i<65|i>122|(i>90&i<97) checks whether the input character i is NOT alphabetic. If so, input is returned. The uppercase alphabet is returned if b==1 and i<97 (uppercase character). If b==1 and i>96, 32 is added to 65:90 that corresponds to 97:122 - the lowercase alphabet. • Nice submission. Two comments: It's common to either use i=input('') if the submission is a script, or as a function argument if it's a function @(i)i^2. i='a' is in general not accepted. Also, you can save 3 bytes by doing [1,2,3,''] instead of char([1,2,3]). Dec 22 '15 at 14:45 • Ok, edited. Thanks for suggestion! Dec 23 '15 at 12:40 # SpecBAS, 111 bytes I've been through several versions of this, 111 seems to be the best I can manage. 1 INPUT l$: a$="abcdefghijklmnopqrstuvwxyz" 2 ?IIF$(l$IN ["a" TO "z","A" TO "Z"],IIF$(l$=UP$ l$,UP$ a$,a$),l\$)


Line 2 uses the ? shortcut for PRINT and nested inline IF statements

Pseudo code explanation

IF character IN "a".."z","A".."Z"
THEN
IF character = UPPERCASE character
THEN
print UPPERCASE alphabet
ELSE
print alphabet
ENDIF
ELSE
print the character
ENDIF

• It's hard to make ["a" TO "z","A" TO "Z"] look more like a pseudo code than it already does. "a".."z","A".."Z" looks more like a "real code", at least in my eyes... Both are very easy to understand though =) Dec 22 '15 at 11:15
• Spec what???? Dec 22 '15 at 13:47

# Swift 2, 142 Bytes

func d(s:String)->String{let a="abcdefghijklmnopqrstuvwxyz";for v in s.utf8{return v>64&&v<91 ?a.uppercaseString:(v>96&&v<123 ?a:s)};return s}


### Ungolfed

func d(s: String) -> String{
let a="abcdefghijklmnopqrstuvwxyz"
for v in s.utf8{
return (
v > 64 && v < 91 ?
a.uppercaseString :
(
v > 96 && v < 123 ?
a :
s
)
)
}
return s
}


# 05AB1E, 19 16 bytes

-3 bytes thanks to else

DAsåiAëDAusåiAuë


How it works

                   # implicit input
D                  # duplicate
A                 # push lowercase alphabet
s                # swap last two elements
å               # push a in b
i              # if
A             # lowercase alphabet
ë            # else
D         # duplicate
Au       # uppercase alphabet
s      # swap last two elements
å     # push a in b
I    # if
Au  # uppercase alphabet
ë # else leave input
# implicit print


Try it online!

• Not sure if ¹ (first input) already existed when you posted your answer, but you can golf 2 bytes with it: A¹åiAëAu¹åiAuë (Try it online or test suite). Aug 9 '18 at 13:57

## Java SE 8, 71 69 bytes

Golfed:

(a,s)->{char b=97;if(a<91)b-=32;a=b;b+=26;while(a<b)s+=a++;return s;}


Ungolfed:

(a,s)->{          // String as a parameter. If declaration is necessary it adds 8 bytes
char b = 97;      // Uppercase A char, this is important
if (a < 91)       // If it is not past 'z', where a is a char param
b -= 32;      // Then go back to the lowercase alphabet
a = b;            // Done to prevent a cast
b += 26;          // End of alphabet
while (a < b)     // Go to end of alphabet
s += a++;     // Append character
return s;}        // Then return


I had originally implemented the following

String s="";char b=96;if(a-91<0)b-=32;for(char c=b;++c<b+27;)s+=c;return s;


It's more elegant but sadly it's one byte larger. This is assuming that behavior for non alpha characters is undefined and string s is initialized to "" prior to execution. Be gentle it's my first post.

edit: 2 bytes saved by Stewie Griffin by changing

a - 91 < 0 to a < 91

• Welcome to the site! :) Nov 9 '17 at 19:59
• Thanks! Been lurking for a few years now and really interested to see if I can make competing Java/C++ answers :)
– jfh
Nov 9 '17 at 20:03
• a<91 should work, or...? Nov 9 '17 at 20:33

# Scala, 91 characters

(c:Char)=>{var a='a'.to('z').mkString;if(c.isUpper)a=a.toUpperCase;if(!c.isLetter)a=""+c;a}


## Un-golfed

def f(c: Char): String = {
var a='a'.to('z').mkString //set up lower case default response
if (c.isUpper) {
a = a.toUpperCase     //mutate the result if upper case
}
if (!c.isLetter) {
a = ""+c                 //mutate the result if not a letter
}
a                         //return result
}


Having a initial mutable result rather than returning an immutable value from 3 distinct if else blocks saved me 2 chars, even though I hate it.

## Scala-thonic method

A better method for scala would be something like this:

def convertToAlphabet(c: Char): String = {
c match {
case x if !x.isLetter => x.toString
case x if x.isUpper => ('A' to 'Z').mkString
case _ => ('a' to 'z').mkString
}
}


# Japt, 9 bytes

;[CBU]æøU
`

Run it online