1

I'm trying to use the "ls" python command in maya, to list certain objects with a matching string in the name in concatination with a wildcard.

Simple sample code like this:

from maya.cmds import *
list = ls('mesh*')

This code works and will return a list of objects with the matching string in the name, however, I would like to use a variable instead of hard coding in the string. More like this:

from maya.cmds import *
name = 'mesh'
list = ls('name*')

OR like this:

from maya.cmds import *
name = 'mesh'
list = ls('name' + '*')

However, in both examples, it returns an empty list unlike the first. I'm not sure why this is the case because in those examples, the string concatination should come out to 'mesh*' like the first example. I couldn't find an answer on this website, so I chose to ask a question.

Thank you.

JD

PS. If there is a better way to query for objects in maya, let me know what it's called and I'll do some research into what that is. At the moment, this is the only way I know of how to search for objects in maya.

JoshD
  • 11
  • 1
  • Take a tour at [String Formatting](https://docs.python.org/3/tutorial/inputoutput.html). You are not referring the variable `name` – Chris Feb 28 '19 at 01:14

1 Answers1

0

As soon as you add quotes around your variable name like this 'name', you are actually just creating a new string instead of referring to the variable.

There are many different ways to concatenate a string in Python to achieve what you want:

Using %:

'name%s' % '*'

Using the string's format method:

'{}*'.format(name)

Simply using +:

name + '*'

All of these will yield the same output, 'mesh*', and will work with cmds.ls

Personally I stick with format, and this page demonstrates a lot of reasons why.

Green Cell
  • 4,677
  • 2
  • 18
  • 49