Reputation: 111
this is my first post here and I am a complete beginner(only been coding for a week or so) so please pardon me if Ive made some very dumb mistakes
Write a function takes a two-word string and returns True if both words begin with the same letter(capitalisation does not matter) and false otherwise
SOLUTION:
def prob2(b):
for p,q in b.split():
if p[0] == q[0]:
return(True)
else:
return(False).
If I try it with a string like 'hello world', I get the error message:
too many values to unpack, expected 2
But if I try it with a string like 'dc' i get the desired output, which makes it obvious that its splitting the string after each letter, not on the whitespace, which is weird, because i did not make any changes and by default it should be splitting on the whitespace.
Please tell me how I can fix this, thanks!
Upvotes: 0
Views: 2149
Reputation: 1
def check_the_first_letter_of_two_words(word):
new_word = word.lower().split()
if new_word[0][0] == new_word[1][0]:
return True
else:
return False
word1 = 'Hello World'
word2 = 'World wide'
check_the_first_letter_of_two_words(word1)
check_the_first_letter_of_two_words(word2)
Upvotes: 0
Reputation: 54148
When doing for p,q in b.split()
this need that every element returned from the split()
can be unpack in 2, this is the case of dc->d,c
but each word of Hello Word
canno't be unpacked in 2
Also you don't need to loop, as you need to look only at the first char, just do
def prob2(content):
words = content.split()
return len(words) == 2 and words[0].lower() == words[1].lower()
Upvotes: 0
Reputation: 77837
b.split()
returns a list of space-separated words. Break this into component steps:
seq = b.split()
p, q = seq[0]
if p[0] == q[0]:
return True
else:
return False
This will work only when the first element of seq
is some iterable of length 2. In short, a 2-letter string will work, comparing those two letters ... d
and c
in your example.
Following the above break-down in your two-word case, we get the attempted assignment
p, q = "hello"
This tries to unpack 5 characters to two variables, causing your error.
Simply splitting a two-word string requires no loop, as others have shown:
p, q = b.split()
Or, safer yet, simply slice off the first two words:
p, q = seq[:2]
seq = seq[2:] # remove the first two words from the `split` sequence
Also, note that your return can be much simpler: you already evaluated the Boolean result you want in the if
expression.
p, q = seq[:2]
return p[0] == q[0]
Upvotes: 1
Reputation: 33285
for p,q in b.split()
is not doing what you think.
Use p,q = b.split()
instead.
Upvotes: 0
Reputation: 6111
it may have more items in the list, when you split the string by white space. you could print it out to see
def prob2(b):
p,q = b.split()
return p[0].lower() == q[0].lower()
Upvotes: 0