Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to slice a string?

Tags:

python

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?

like image 693
sqram Avatar asked Jun 18 '09 05:06

sqram


People also ask

How do you slice a string?

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.

How is string slicing done?

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.

What is a string slice give an example?

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.

Can u slice a string?

Because strings, like lists and tuples, are a sequence-based data type, it can be accessed through indexing and slicing.


1 Answers

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").

like image 56
Anurag Uniyal Avatar answered Nov 15 '22 16:11

Anurag Uniyal