Normally, you would just do:
s = s[:-3] + s[-2:]
The s[:-3] gives you a string up to, but not including, the comma you want removed ("this is a string") and the s[-2:] gives you another string starting one character beyond that comma (" a").
Then, joining the two strings together gives you what you were after ("this is a string a").
String slicing in Python script
Python strings slicing - Stack Overflow
Is string slicing actually useful in real world applications?
Doubt in String Slicing
Normally, you would just do:
s = s[:-3] + s[-2:]
The s[:-3] gives you a string up to, but not including, the comma you want removed ("this is a string") and the s[-2:] gives you another string starting one character beyond that comma (" a").
Then, joining the two strings together gives you what you were after ("this is a string a").
A couple of variants, using the "delete the last comma" rather than "delete third last character" are:
s[::-1].replace(",","",1)[::-1]
or
''.join(s.rsplit(",", 1))
But these are pretty ugly. Slightly better is:
a, _, b = s.rpartition(",")
s = a + b
This may be the best approach if you don't know the comma's position (except for last comma in string) and effectively need a "replace from right". However Anurag's answer is more pythonic for the "delete third last character".
The step count given by you in s[0:-5:-1] is -1, which means that string slicing will be reverse like 'a','v','i','S'.
But you are starting from s[0] which is "S" and due to the step count -1, it will print the previous character from the string "Siva". But there are no characters before 'S'. That's why it's stopping and only printing 'S'.
If you want the reverse of s = "Siva", then simply write s[::-1].
Slicing is s[start:end:step] so if you want Savi you have to do
s[0] + s[-1:0:-1]
- Start at -1 means start at the end of the string.
- End at 0 means end at the beginning ignoring this first character.
- Step -1 means go reverse one at a time.
Im doing an online bootcamp at the moment and they've spent a fair bit of time going over string slicing. I couldnt help but think theres little to no real world uses for this stuff. Am I incorrect? if so what is a reasonable scenario in which you would **need** string slicing?