首页 > 技术文章 > python中的字符串常量,是否支持通过下标的方式赋值

chuanzhang053 2018-11-23 12:36 原文

说明

  今天在看python,通过下标获取字符串常量的字符,在想是否可以通过下标的方式赋值。

操作

1.对字符串下标赋值

>>> text='python'
>>> text[2] = 'j'
Traceback (most recent call last):
  File "<pyshell#128>", line 1, in <module>
    text[2] = 'j'
TypeError: 'str' object does not support item assignment

 

备注:不能以这种方式进行赋值,本来就是字符串常量,下标就是一个不变的字符。不能赋值。

2.但是可以通过下标的方式,使用加号 + 操作符拼接出一个新字符串

>>> text[2] + 'j'
'tj'
>>> text[:2] + 'py'
'pypy'

 

 

文档创建时间:2018年11月23日12:35:10

推荐阅读