【问题标题】:How do I capitalize all occurrences of the word 'I' in a string? Python如何将字符串中所有出现的单词“I”大写? Python
【发布时间】:2020-11-16 01:09:28
【问题描述】:

我正在尝试将所有出现的单词“I”大写,而不是字母“i”。

输入:this is my input, how do i do capitalize the word i?

预期:this is my input, how do I do capitalize the word I?

我尝试了一个简单的.replace('i', 'I'),但显然这不起作用。

【问题讨论】:

    标签: python python-3.x string replace


    【解决方案1】:

    使用正则表达式,将i与两边的单词边界\b匹配。

    import re
    
    output_string = re.sub(r'\bi\b', 'I', input_string)
    

    【讨论】:

      【解决方案2】:

      使用带有“i”周围单词边界的正则表达式来替换它:

      import re
      
      re.sub(r"\bi\b", "I", "this is my input, how do i do capitalize the word i?")
      # outputs "this is my input, how do I do capitalize the word I?"
      

      阅读here 了解更多关于词绑定的信息。

      【讨论】:

        猜你喜欢
        • 2017-04-04
        • 1970-01-01
        • 2023-03-13
        • 2018-05-27
        • 2013-10-24
        • 2013-02-28
        • 2023-03-10
        • 1970-01-01
        • 2022-11-24
        相关资源
        最近更新 更多