赞
踩
We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
Let's try to understand this with an example.
You are given an immutable string, and you want to make chaneges to it.
>>> sting = "abracadabra"
>>> print string[5]
a
>>> sting[5] = 'k'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assigment
>>> stirng = "abracadabra"
>>> a = list(string)
>>> a[5] = 'k'
>>> string = ''.join(a)
abrackdabra
>>> string = string[:5] + "k" + string[6:]
>>> print string
abrackdabra
Read a given string, change the character at a given index and then print the modified string.
Complete the mutate_string function in the editor below.
mutate_string has the following parameters:
* string string : the string to change
* int position: the index to insert the character at
* string character: the character to insert
* string: the altered string
The first line contains a string.
The next line contains an integer position, the index location and a string character, separated by a space.
STDIN Function
------ -----------
abracadabra s = 'abracadabra'
5 k position = 5 , character = 'k'
abrackdabra
- def mutate_string(string, position, character):
- a = list(string)
- a[position] = character
- string = ''.join(a)
- return string
-
- if __name__ == '__main__':
- s = input()
- i, c = input().split()
- s_new = mutate_string(s, int(i), c)
- print(s_new)
元组(tuple)在Python中是不可变数据类型,这意味着一旦创建,就不能更改其内容,包括不能添加、删除或修改元组中的元素。
虽然不能修改元组中的元素,但你可以通过以下方式“重新赋值”:
示例:
- # 创建一个元组
- t = (1, 2, 3)
-
- # 尝试修改元组中的元素(这将引发TypeError)
- try:
- t[1] = 20
- except TypeError as e:
- print(e) # 输出错误信息
-
- # 创建一个新的元组,并赋予相同的变量名
- t = (1, 20 ,3)
- print(t) # 输出:(1, 20, 3)
-
- # 使用切片和连接创建一个新元组
- t = t[:1] + (20,) + t[2:]
- print(t) # 输出:(1, 20, 3)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。