0

So I tried to swap the first characters of the strings. Fresh > Nresh and Not fresh > Fot fresh, what am I doing wrong here? I got this error message: string_A[0] = string_B[0:1] TypeError: 'str' object does not support item assignment

Here my code:

string_A = "Fresh"
string_B = "Not fresh"

placeholder = string_A[0]
string_A[0] = string_B[0]
string_B[0] = string_A[0]

print(string_A)
print(string_B)
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
kcr
  • 37
  • 2
  • 10
  • 2
    Strings are immutable. – NobbyNobbs Mar 16 '21 at 13:58
  • 1
    This question has been at: https://stackoverflow.com/questions/10631473/str-object-does-not-support-item-assignment-in-python/18006499 – raushanraja Mar 16 '21 at 14:01
  • As alternative to the answers under the link provided above, `string_A.replace(string_A[0], string_B[0], 1)` would yield the behavior you're looking for; under the hood it's not different from what is presented, though. – Uvar Mar 16 '21 at 14:03

3 Answers3

1

You can't modify the string objects as they are immutable.

You can overwrite them using slicing:

string_A = "Fresh"
string_B = "Not fresh"

placeholder = string_A[0]
string_A = string_B[0] + string_A[1:]
string_B = placeholder + string_B[1:]

print(string_A)
print(string_B)

You can do it in one line as:

string_A, string_B = string_B[0] + string_A[1:], string_A[0] + string_B[1:]
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

String (str) are immutables in Python.

You need to create a new string and affect it to the same identifier to get the result you want :

string_A = "Fresh"
string_B = "Not fresh"

placeholder = string_A[0]
string_A = string_B[0] + string_A[1:]
string_B = placeholder + string_B[1:]

print(string_A)
print(string_B)
Cyrille Pontvieux
  • 2,356
  • 1
  • 21
  • 29
0

Strings are immutable which means you can't update. Following is one way of doing what you asked for:

string_A = "Fresh"
string_B = "Not fresh"

a =  string_B[0:1] + string_A[1:]
b =  string_A[0:1] + string_B[1:]
print(a)
print(b)