-1
def a_letter(string):
  s = string.lower()
  if s[0] == 'a':
    return 'alpha'
  else:
    return 'zebra'

This code is testing the first letter of a string - if it's an 'a' then return alpha, else return zebra. Is there a better way to do this?

Jongware
  • 21,685
  • 8
  • 47
  • 95
sammiie
  • 31
  • 7

4 Answers4

3

I think a good way to do so is:

def a_letter(s):
    return 'alpha' if s and s[0].lower() == 'a' else 'zebra'

Because it is clear and sufficiently concise.

timgeb
  • 73,231
  • 20
  • 109
  • 138
vinzee
  • 17,022
  • 14
  • 42
  • 60
1

If you have only two conditions you can try something a poor-man's conditional expression

print(['zebra','alpha'][string[0].lower() =='a'])

How it works ?

True == 1, False == 0

because booleans are a subclass of int , so [string.lower()[0]=='a'] produce a integer value but ['false','true'] takes it as index value.

Aaditya Ura
  • 10,695
  • 7
  • 44
  • 70
0

There is nothing inherently wrong with being explicit. Maybe you should protect against the empty string as pointed out by Willem Van Onzem in the comments. You can do that - for instance - by using str.startswith which is the built-in way to check for prefixes. And are there shorter ways? - Sure:

return ('zebra', 'alpha')[s.startswith(('a', 'A'))]

Or maybe more readable, using the ternary operator:

return 'alpha' if s.startswith(('a', 'A')) else 'zebra'
user2390182
  • 67,685
  • 6
  • 55
  • 77
0

Do a more comprehensive solution, return something for every letter

voc= converts the list of nato alphabet names to a dict mapping of letter to name

def phonetic checks the input is in the dict and then returns the value, or ? if it is confused

voc=dict([[string.lower(x[0]), x] for x in 
['ALFA',
 'BRAVO',
 'CHARLIE',
 'DELTA',
 'ECHO',
 'FOXTROT',
 'GOLF',
 'HOTEL',
 'INDIA',
 'JULIETT',
 'KILO',
 'LIMA',
 'MIKE',
 'NOVEMBER',
 'OSCAR',
 'PAPA',
 'QUEBEC',
 'ROMEO',
 'SIERRA',
 'TANGO',
 'UNIFORM',
 'VICTOR',
 'WHISKEY',
 'XRAY',
 'YANKEE',
 'ZULU']])

def phonetic(letter):
    if letter in voc:
        return voc[letter]
    else:
        return "?"
Vorsprung
  • 30,988
  • 4
  • 36
  • 58