0

I need to check whether a two-word string start with same string (letter) should return True. I am not sure which slicing method apply here. I gone through the various post here but could not find the required one. Based on my code, the result always give 'none'.

def word_checker(name):
    if name[0] =='a'  and name[::1] == 'a':
        return True

print(word_checker('abc adgh'))
jpp
  • 159,742
  • 34
  • 281
  • 339
Abhi
  • 29
  • 1
  • 5

2 Answers2

1

You need to split the string on spaces and check the first letter of each split:

def word_checker(name):
    first, second = name.split()
    return first[0] == 'a' and second[0] == 'a'

print(word_checker('abc adgh'))

Output

True

But the previous code will only return True if both words start with 'a', if both must start with the same letter, you can do it like this:

def word_checker(name):
    first, second = name.split()
    return first[0] == second[0]

print(word_checker('abc adgh'))
print(word_checker('bar barfoo'))
print(word_checker('bar foo'))

Output

True
True
False
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

'abc adgh'[::1] will simply return the entire string. See Understanding Python's slice notation for more details (list slicing is similar to string slicing).

Instead, you need to split by whitespace, e.g. using str.split. A functional method can use map with operator.itemgetter:

from operator import itemgetter

def word_checker(name):
    a, b = map(itemgetter(0), name.split())
    return a == b

print(word_checker('abc adgh'))  # True
print(word_checker('abc bdgh'))  # False
jpp
  • 159,742
  • 34
  • 281
  • 339