Replace one character in the Python string

Asked 2 years ago, Updated 2 years ago, 16 views

a='A'
g=10
a[0]='g'
print(a[0])

I want to change 'A' of a to 'g' value, but why is there an error?

python

2022-09-21 10:43

1 Answers

String is an immutable type and cannot be modified,
As if you can't change the value of the tuple.
So if you want to change the string, you need to use replace or list.

Use list
When you want to change the position you want.

a = 'asd'
a = list(a)  # ['a', 's', 'd']
a[0] = 'kk'  # ['kk', 's', 'd']
print(''.join(a))  # 'kksd'

replaceutilization
When you want to change the string of a particular pattern

a = 'asda'
a.replace('a', '12')  # '12sd12'

If you change the contents of Gauguin's inquiry as above, it is as follows.

a = 'A'
g = 10
a = list(a)
a[0] = str(g)  # ['10']
print(''.join(a))  # '10'


2022-09-21 10:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.