怎么做python字替换?

时间:2017-10-06 04:48:34

标签: python regex string replace

我想从字符串中替换一些。例如。 'eq'到'=','gt'到'>'

举一个这样的例子:

s = "name eq 'alex' and age gt 36" to "name = 'alex' and age > 36"

我不能使用string.replace(),因为它替换了字符。 我应该拆分句子然后re.sub(r'^eq$', '=', s)吗?是否有捷径可寻?

PS。我不想s.replace(' eq ', ' = '),因为字符串的开头或结尾可能有单词。例如,将我替换为sender eq me中的'alex'会导致sender = 'alex'

6 个答案:

答案 0 :(得分:1)

似乎replace是完美的解决方案。

s = "name eq 'alex' and age > 36" 
goal = "name = 'alex' and age > 36"
s = s.replace(" eq ", " = ")

s == goal

答案 1 :(得分:1)

使用正则表达式替换。它将避免误导效应。

import re

s = ("name eq 'alex' and age > 36 equity eq\n"
    "{ dictionary: \"\" } eq { dictionary: \"\" }\n"
    "\"string\" eq \"string\"\n"
    "var eq var\n"
    "[\"list\"] eq [\"list\"]\n"
    "(\"tuple\") eq (\"tuple\")")

regex_template_start = r"(?<=[' \"\w\[\]\(\)\{\}])\b"
regex_template_end   = r"\b(?=[' \"\w\[\]\(\)\{\}])"

s = re.sub(r"{0}{1}{2}".format(regex_template_start, "eq", regex_template_end), '=', s)
s = re.sub(r"{0}{1}{2}".format(regex_template_start, "gt", regex_template_end), '>', s)

print(s)

查看结果:https://repl.it/MLpM/5

<强>解释

  

Python变量规则变量名称必须以字母或字母开头   下划线,例如:

     
      
  • _underscore
  •   
  • underscore_
  •   
     

变量名的其余部分可能包含字母,数字   和下划线。

     
      
  • password1
  •   
  • 的n00b

  •   
  • un_der_scores

  •   

因此正则表达式必须涵盖变量名称情况。 此外,它可以是元组,字典或列表,因此正则表达式也包括[]{}()

答案 2 :(得分:0)

这里我们使用REGEX来实现所需的输出。

正则表达式: (?:(?<=^)|(?<=\s))eq(?=\s|$)

  1. 这将匹配eqstart of string ^space \s的正面展示,以及end of string $space \s
  2. 的正向展望

    解决方案1:

    Regex demo

    import re
    s = "name eq 'alex' and age > 36"
    print re.sub('(?:(?<=^)|(?<=\s))eq(?=\s|$)',"=",s)
    print re.sub('(?:(?<=^)|(?<=\s))gt(?=\s|$)',">",s)
    

    Try this code snippet here

    解决方案2:

    您可以这样做,将space-eq-space替换为space-=-space

    根据您的要求,您eq之前和之后space eqs = "name eq 'alex' and age > 36" print s.replace(" eq "," = ").replace(" gt ", " > ")

    Try this code snippet here

    <nav class="navbar dashboard-nav">
    <div class="container-fluid">
        <ul class="nav navbar-nav dashboard-menu" id="dashboard-menu-lst">
            <li class="dropdown">
                <a class="dropdown-toggle" data-original-title="" href="/dashboard/buying/home.html" title="">Buying <span class="caret"></span></a>
                <ul class="dropdown-menu drpdwn-submenu">
                    <li class="dashboard-drpdwn-pointer"></li>
                    <li>
                        <a data-original-title="" href="/dashboard/buying/submit-RFQ.html" title="">Submit RFQ</a>
                    </li>
                    <li>
                        <a data-original-title="" href="/dashboard/buying/manage-RFQ.html" title="">Manage RFQ</a>
                    </li>
                    <li>
                        <a data-original-title="" href="/dashboard/buying/inquiries-sent-by-me.html" title="">Inquiries Sent by Me</a>
                    </li>
                </ul>
            </li>
            <li class="dropdown topbar-drpdwn">
                <a class="dropdown-toggle" data-original-title="" href="/dashboard/selling/home.html" title="">Selling <span class="caret"></span></a>
                <ul class="dropdown-menu drpdwn-submenu">
                    <li class="dashboard-drpdwn-pointer"></li>
                    <li>
                        <a data-original-title="" href="/dashboard/selling/inquiries-received-by-me.html" title="">Inquiries Received by Me</a>
                    </li>
                    <li>
                        <a data-original-title="" href="/dashboard/selling/quotations-sent-by-me.html" title="">Quotations Sent by Me</a>
                    </li>
                    <li>
                        <a data-original-title="" href="/dashboard/selling/quotation-invites-received-by-me.html" title="">Invites Received by Me</a>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
    

答案 3 :(得分:0)

您可以使用简单的for循环来避免更改“eq”和“gt”的其他实例

# split on space character
words = s.split(' ')    

# loop and check every word
for i, w in enumerate(words):    

    # replace occurrence of r'^eq$'
    if w == 'eq':    
        words[i] = '='

    # replace occurrence of r'^gt$'
    elif w == 'gt':     
        words[i] = '>'

s = ' '.join(words)

答案 4 :(得分:0)

只需使用 re.sub 功能

即可
import re
s = "name eq 'alex' with equity gt 36"
s = re.sub(r'\s{1}eq\s{1}', ' = ', s)
s = re.sub(r'\s{1}gt\s{1}', ' > ', s)
print(s)

输出 name =&#39; alex&#39;公平&gt; 36 正是你想要的

答案 5 :(得分:0)

一种解决方案是创建一个字典,其中包含需要替换的所有值的key:value。 将字符串拆分为列表可解决问题,例如

equity
,其中也包含单词eq

dicta = {
    "eq" : "=",
    "gt" : ">",
    "lt" : "<"
}

我试过替换字典中列表中的单词。它不是完美的,但是另一种方法来完成这项任务。我正在尝试更新它。

s = "name eq 'alex' and age gt 36"
[s.replace(char, dicta.get(char)) for char in s.split(" ") if char in dicta ]