推荐学习书目
› 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
css3
V2EX  ›  Python

replace 怎么分别替换一个字符串中相同的字符?(已找到答案)

  •  
  •   css3 · Oct 31, 2018 · 2614 views
    This topic created in 2892 days ago, the information mentioned may be changed or developed.

    如下示例,我想把 a 字符串中的第一个 A 替换成 g , 把第二个 A 替换成 n , 发现用 replace 指定位置替换,扔是全局替换所有的 A,怎么分别替换 2 个 A 的不同值呢?

    >>> a = '84A6d8er621bfA1d4'
    a.replace(a[2], "g")
    >>> '84g6d8er621bfg1d4'
    
    
    

    我是想要 a = '84g6d8er621bfn1d4'

    额,发现了 replace 函数可以带一个替换次数的参数,参数设成 1,就只替换第 1 个了 这样搞定了

    a.replace(a[2], "g",1).replace(a[13], "n",1)
    
    
    1 replies  •  2018-10-31 20:51:13 +08:00
    xubeiyan
        1
    xubeiyan  
       Oct 31, 2018 via Android
    replace 第三个参数指定替换次数,你调两次不就行了
    a.replace("A", "g", 1).replace("A", "n", 1)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2298 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 06:17 · PVG 14:17 · LAX 23:17 · JFK 02:17
    ♥ Do have faith in what you're doing.