V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dddd
V2EX  ›  Python

Python 的字符串以索引的方式赋值时直接创建一个新的字符串对象不行吗?

  •  
  •   dddd · Jan 5, 2015 · 4210 views
    This topic created in 4130 days ago, the information mentioned may be changed or developed.

    我知道数字,字符串,元组都是不可变对象,自身是无法改变的,对其操作会创造一个新的对象。


    数字可以像这样创建一个新对象

    >>> a = 1
    >>> id(a)
    42479960
    >>> a = 2
    >>> id(a)
    42479936
    

    字符串以索引赋值的时候会报错,为什么不再创建一个新的字符串对象,这样不好吗?不这样实现是有其它的缺陷还是 Python 故意的,Python 的信仰?

    >>> s = 'abc'
    >>> s[1]
    'b'
    >>> s[1] = 'd'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    
    3 replies    2015-01-05 15:39:13 +08:00
    glasslion
        1
    glasslion  
       Jan 5, 2015
    如果 s[1] = 'd' 会产生一个新的字符串, 你怎么得到它的引用?
    dddd
        2
    dddd  
    OP
       Jan 5, 2015
    好吧!自己SB了,数字(1,2,3),字符串('abc')才是对象,`a = 1`, `b = 'abc'`中的 a, b只是对其的的引用,一个标示而已。

    话说我创建的主题怎么删除?
    imn1
        3
    imn1  
       Jan 5, 2015
    请站长,但站长从不理会这个请求,你的SB证据会一直保留,^_^
    也不算SB了,大部分学py的都经过这个,必由之路
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3538 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 00:03 · PVG 08:03 · LAX 17:03 · JFK 20:03
    ♥ Do have faith in what you're doing.