【问题标题】:Replacing specific characters in python string替换python字符串中的特定字符
【发布时间】:2017-06-08 06:29:52
【问题描述】:

我有一个字符串是

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

我想将特定的一组 ' 替换为 %。它必须看起来像

string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

我正在尝试使用替换功能。但未能得到确切的结果。

【问题讨论】:

  • 您能否更具体地说明您尝试更换的方式。是否替换了类似于 ' 的大写字母?

标签: python string text


【解决方案1】:

你可以使用regex:

>>> import re
>>> re.sub(r"'([^']+)': '([^']*)'", r"%\1%: '\2'", string)
"create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

【讨论】:

    【解决方案2】:

    使用re 替换模式。

    >>> import re
    >>> s = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"
    >>> S=re.sub(r"\'([A-Z]*)\'",r"%\1%",s)
    create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})
    

    【讨论】:

      【解决方案3】:
      string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"
      
      w = string.find('{')+ 1
      x = w + 10;t = w + 22;y = w + 31;z = w + 43;q = w + 48
      w1=string[w].replace("'",'%')
      x1=string[x].replace("'",'%')
      t1=string[t].replace("'",'%')
      y1=string[y].replace("'",'%')
      z1=string[z].replace("'",'%')
      q1=string[q].replace("'",'%')
      
      print(string[0:23]+w1+string[24:33]+x1+string[34:45]+t1+string[46:54]+y1+string[55:66]+z1+string[67:71]+q1+string[72:])
      

      希望这是你想要的。

      【讨论】:

        猜你喜欢
        • 2017-05-03
        • 1970-01-01
        • 2012-08-09
        • 1970-01-01
        • 2014-07-22
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多