Is there a way to compare the first character of a string to the last character without knowing the amount of characters in it? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

Is there a way to compare the first character of a string to the last character without knowing the amount of characters in it?

Is there a way to compare the first character of a string to the last character without knowing the amount of characters in it? (Python)

1st Jun 2022, 5:22 PM
bee
bee - avatar
4 Respuestas
+ 8
mystr[0] == mystr[-1] string slice techique
1st Jun 2022, 7:20 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 6
The index of the first character is 0. The len() function can give you the length of a string, but since indices start at 0, the maximum index (last character) is 1 less than the length. The expression: myStr[0] == myStr[len(myStr) - 1] evaluates to true if the first and last character are the same and false if they are not. EDIT: You can also use myStr[-1] to get the final character. I’ve never really liked that approach, but it’s arguably more efficient and more legible; negative indices count from the end. The equivalent expression to the one above is: myStr[0] == myStr[-1]
1st Jun 2022, 5:40 PM
Jeremy Miller
+ 5
Rik Wittkopp , it's indexing, not slicing: ("Dog","Cat")[1] -> Cat there might be a misunderstanding by calling this a slice. this is what we understand as: -> indexing: indexing is used to obtain an individual element -> slicing: slicing is used to obtain a sequence of elements
2nd Jun 2022, 2:14 PM
Lothar
Lothar - avatar
+ 1
Lothar Thanks for that. I recently had a misunderstanding with rotation vs combination. Is there a trend I wonder 🤪😳 🤣👍
2nd Jun 2022, 10:41 PM
Rik Wittkopp
Rik Wittkopp - avatar