-2

As string is immutable,so we can't change the string so how we can insert a character at middle position?

code:

s = "hello world"
s[5] = '-'

But it gives you error as it is immutable.so,how we can resolve this problem?

1
  • 1
    A quick search will give you your answer - no, strings are not mutable. Commented Oct 17, 2021 at 4:28

2 Answers 2

1

We know string is immutable,but we can't change values through assignment operator.so we can acheive this through string slicing:

s = s[:5]+'-'+s[6:]

so now s becomes "hello-world". so this can be done using string slicing.

Sign up to request clarification or add additional context in comments.

3 Comments

But note that s is now a new string. If s was passed as an argument to a function, the value of s in the function is now hello-world, but the caller still sees the original string hello world
@FrankYellin Then you should use global keyword inside function
That only helps if the caller also named their argument s and remembers to declare it global.
0

Yes , the strings in the Python are immutable. But we can perform concatenate operation on strings.

If we want to modify string like..

S = "Hello World" S[5] = '-'

It is not possible but we can do this by slicing method

S = S[:5] + '-' + S[6:] Then the result is S = "Hello-World"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.