-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
  • 22,200
  • 8
  • 54
  • 100
sammiie
  • 41
  • 8

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
  • 76,762
  • 20
  • 123
  • 145
vvvvv
  • 25,404
  • 19
  • 49
  • 81
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
  • 12,007
  • 7
  • 50
  • 88
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
  • 72,016
  • 6
  • 67
  • 89
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
  • 32,923
  • 5
  • 39
  • 63