+ 1
Python program to get first cha. Last chat. And 2 middle chat. From a string
1 Answer
+ 4
The first and last letters of any string can be easily extracted using indexing: s[0] and s[-1] respectively.
The exact middle 2 letters can only be found if the string has an even number of characters. This can be done with slicing:
start = (len(s)-1) // 2
end = len(s) // 2 + 1
s[start:stop] # string slice
Note that for strings with odd number of characters, it will only return the single middle character. Indexing and slicing can be used for any sequence (lists, tuples,..), not just strings.