【问题标题】:How to convert specific character sequences in a string to upper case using Python?如何使用 Python 将字符串中的特定字符序列转换为大写?
【发布时间】:2010-10-29 06:15:02
【问题描述】:

我希望完成以下工作,并想知道是否有人对如何最好地完成它有建议。

我有一个字符串,比如 'this-is,-toronto.-and-this-is,-boston',我想将所有出现的 ',-[az]' 转换为 ',-[AZ ]'。在这种情况下,转换的结果将是“this-is,-Toronto.-and-this-is,-Boston”。

我一直在尝试使用 re.sub(),但还没有弄清楚如何

testString = 'this-is,-toronto.-and-this-is,-boston'
re.sub(r',_([a-z])', r',_??', testString)

谢谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    re.sub 可以接受一个返回替换字符串的函数:

    import re
    
    s = 'this-is,-toronto.-and-this-is,-boston'
    t = re.sub(',-[a-z]', lambda x: x.group(0).upper(), s)
    print t
    

    打印

    this-is,-Toronto.-and-this-is,-Boston
    

    【讨论】:

    • +1,打败我 :) 我的匹配整个单词并调用 x.group(0).capitalize,但你的工作方式相同,可能更快。
    • 谢谢大家!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2021-06-11
    • 2017-05-16
    • 1970-01-01
    相关资源
    最近更新 更多