I have a string, example:
s = "this is a string, a"
Where a ','
(comma) will always be the 3rd to the last character, aka s[-3]
.
I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task.
How can I accomplish this in a simpler way?
The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.
For understanding slicing we will use different methods, here we will cover 2 methods of string slicing, the one is using the in-build slice() method and another using the [:] array slice. String slicing in Python is about obtaining a sub-string from the given string by slicing it respectively from start to end.
It's known as string slicing. The syntax that you use looks really similar to indexing. Instead of just one value being put in the square brackets, you put two with a colon ( : ) in between the two. So in this example, s is the string and m and n are the two values.
Because strings, like lists and tuples, are a sequence-based data type, it can be accessed through indexing and 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"
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With