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)
4 ответов
+ 8
mystr[0] == mystr[-1]
string slice techique
+ 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]
+ 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
+ 1
Lothar
Thanks for that.
I recently had a misunderstanding with rotation vs combination.
Is there a trend I wonder 🤪😳
🤣👍