0

Suppose I have the string x='abcd'. I want to replace the first and last letters of the string with c so that it becomes x='cbcc'. I'm a beginner at programming so I do not know how to do this.

John
  • 11
  • 4

2 Answers2

0

You use indexing to access the first and last letters:

>>> s = "hello"
>>> s[0]
'h'
>>> s[-1]
'o'

However, you can't assign different characters to string literals:

>>> s[0] = "x"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

You must rebuild the string:

>>> s = "x" + s[1:]
>>> s
'xello'

Where s[1:] splices the string from the first character to the end.

I hope this helps you with your task.

TerryA
  • 58,805
  • 11
  • 114
  • 143
0

In Python, strings are immutable. This means you can't simply jump in and change one part of a string. What you can do is select a specific part of a string (called a slice) and add strings (in this case individual characters) to either end of the slice.

What I am doing below is selecting all of the characters of the string except the first and last, and then adding the desired strings to each end.

Try this:

x='abcd'

new_x = 'c' + x[1:-1] + 'c'

Also, note that while I have created a new variable new_x, you could also reassign the this new string to the original variable name, i.e., x = 'c' + x[1:-1] + 'c'

William
  • 83
  • 8
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Brett DeWoody Mar 24 '18 at 00:09
  • I agree, good point. Editing it now. – William Mar 25 '18 at 16:08