Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to divide string inside list comprehension

Tags:

python

Asked of me: By filtering the lowers list, create and print a list of the words for which the first half of the word matches the second half of the word. Examples include "bonbon", "froufrou", "gaga", and "murmur".

What i have so far:

[word for word in lowers if list.(word)(1:len(word)/2:)==list.(word)(len(word)/2::)]

Im not sure how to make word a list so I can only use certain characters for this filter. I know this will not work but its my logic so far.

like image 781
user1698174 Avatar asked Dec 05 '25 14:12

user1698174


2 Answers

Logical Error: You're slicing from index 1 instead of 0 in list.(word)(1:len(word)/2:)

Syntax Errors: list.(word) is incorrect syntax, and list slicing uses [ ] not ( ). Simply use word[start:stop] to break it up

Use:

[word for word in lowers if word[:len(word)//2]==word[len(word)//2:]]

Edit: Thanks to Ignacio Vazquez-Abrams' comment - Use integer division ( // operator ) for Python 3 compatibility

like image 99
Anuj Gupta Avatar answered Dec 08 '25 02:12

Anuj Gupta


Try this:

[word for word in lowers if word[len(word)//2:] == word[:len(word)//2]]

like image 26
arshajii Avatar answered Dec 08 '25 04:12

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!