1

So I already know how to remove a index like this:

i = "hello!"
i= i[:0] + i[1:]

print(i)
'ello!'

But how do I replace it? So maybe I wanted to now put a H where the old h was but if I do this: i[0] ="H" I get this error:

Traceback (most recent call last): File "<pyshell#2>", line 1, in i[0] ="H" TypeError: 'str' object does not support item assignment

How do I fix this?

Liam Hall
  • 43
  • 2
  • 9

4 Answers4

2

Strings are immutable in Python, so you can't assign like i[0] = 'H'. What you can do is convert the string to list, which is mutable, then you can assign new values at a certain index.

i = "hello!"
i_list = list(i)

i_list[0] = 'H'

i_new = ''.join(i_list)

print(i_new)
Hello!
Epsi95
  • 8,832
  • 1
  • 16
  • 34
0

This is a duplicate of this post

As said there you have to make a list out of your string and change the char by selecting an item from that list and reassigning a new value and then in a loop rebuilding the string.

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
DeadSec
  • 808
  • 1
  • 12
  • 38
0
i = "hello!"
print(i)  ## will print hello!
i = "H" + i[1:]
print(i) ## will print Hello!
Oliver Robie
  • 818
  • 2
  • 11
  • 30
0

Without creating a list you could also do:

i = "hello!"
i = "H" + i[1:]

More general:

def change_letter(string, letter, index):  # note string is actually a bad name for a variable
    return string[:index] + letter + string[index+1:]

s = "hello!"
s_new = change_letter(s, "H", 0)
print(s_new)
# should print "Hello!"

Also note there is a built in function .capitalize()