Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I splice a string?

Tags:

python

string

I know I can slice a string in Python by using array notation: str[1:6], but how do I splice it? i.e., replace str[1:6] with another string, possibly of a different length?

like image 893
mpen Avatar asked Jun 11 '11 17:06

mpen


People also ask

How do you splice strings?

Definition and UsageThe 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.

Can splice work on strings?

Javascript splice is an array manipulation tool that can add and remove multiple items from an array. It works on the original array rather than create a copy. It 'mutates' the array. It doesn't work with strings but you can write your own functions to do that quite easily.

Can Slicing be done in string?

Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

Can you splice strings in python?

You can't do this since strings in Python are immutable.


1 Answers

Strings are immutable in Python. The best you can do is construct a new string:

t = s[:1] + "whatever" + s[6:]
like image 168
Sven Marnach Avatar answered Sep 24 '22 01:09

Sven Marnach