name.replace xX with y if x exists

时间:2013-07-29 12:53:04

标签: python replace

更具体地说,我想知道如何: name.replace xX with y if if exists,如果不存在则只替换X

我已经在这个论坛上搜索了一个小时,把它变成了两个,我发现的是如何用另一个替换一个东西,现在很容易。

/ A

4 个答案:

答案 0 :(得分:4)

你可以跑:

output = name.replace('xX','y').replace('X','y')

示例:

name = "123xX345X" 
output = "123y345y"

答案 1 :(得分:2)

听起来像是正则表达式的作业x?X

>>> import re
>>> text = " test xX blabla"
>>> re.sub('x?X', 'y', text)
' test y blabla'
>>> text = " test X blabla"
>>> re.sub('x?X', 'y', text)
' test y blabla'

引自docs关于?标记:

  

问号字符?匹配一次或零次;您   可以认为它标记为可选的东西。例如,   home-?brew匹配自制或家庭酿造。

答案 2 :(得分:1)

if 'x' in name:
    name = name.replace('xX','y')
else:
    name = name.replace('X','y')

答案 3 :(得分:1)

从上面的例子来看,这是一个稍微复杂的问题。你必须确保在根命名空间中进行重命名,否则事情会变得很糟糕。你也冒着在孩子面前重新命名父母的风险,这将使得一次打电话给ls很难得到孩子。所以:

def replace_with_any_namespace(src, tgt):
  cmds.namespace(set=":")
  results = {}
  xforms  = cmds.ls(r=True, tr=True, l=True)  # use long paths and recursive to get all namespaces
  xforms = [i for i in xforms if src in i]    # only work on items with your target pattern
  xforms.sort()  
  xforms.reverse()  # sort and reverse means children get renamed before parents
  for item in xforms:
      path, sep, shortname = item.rpartition("|") # gets only the last name
      newname = shortname.replace(src, tgt) # this should be fine even if the namespace is there
      results[item] = cmds.ls(cmds.rename ( item,  newname), l=True)[0]
      # the paths and returns are all long paths so there are no ambiguities
  return results

您是否尝试将其移出命名空间?这更容易:

cmds.namespace(mv = ("R", ":"), force=True)

将R:*中的所有内容移动到基本命名空间。但是,这可能会导致一些重命名。您可能希望在调用之前将重要节点放入集合中,以便找到它们。