0

This is in python and I'm having a little trouble finding this out, I put.

s = 'goodbye'

and I want to know if the first letter is a g. so i put

s[0] = 'g'

but i get an error, what is the right way to finding this?

2 Answers2

2

A single = means 'assignment', and doing two == means 'compare and see if they're equal'. The difference between the two can be subtle (just a single character difference!), so make sure you don't get confused between the two

You want s[0] == 'g':

if s[0] == 'g':
    print "word starts with 'g'"

Doing s[0] = 'g' is telling Python "change the first letter of the string to 'g'". However, that fails because in Python, strings are immutable -- they can never be changed.

Community
  • 1
  • 1
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
0

You could use the startswith(prefix) method (returns True if string starts with the prefix, otherwise returns False):

>>> s = 'hello'
>>> a = s.startswith('h')
>>> a
True
Miguel Prz
  • 13,718
  • 29
  • 42