V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2018-10-31 20:39:21 +08:00 · 2020 次点击
    这是一个创建于 1997 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如下示例,我想把 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 条回复    2018-10-31 20:51:13 +08:00
    xubeiyan
        1
    xubeiyan  
       2018-10-31 20:51:13 +08:00 via Android
    replace 第三个参数指定替换次数,你调两次不就行了
    a.replace("A", "g", 1).replace("A", "n", 1)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2698 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:18 · PVG 18:18 · LAX 03:18 · JFK 06:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.