Python string operators

Noob question here

    
print '%s' % (CTRL + name)

returns ‘CTRL_Shoulder


    newCtrl = cmds.circle(n='%s', nr=(1, 0, 0)) % (CTRL + name)

returns ‘unsupported operand type(s) for %: ‘list’ and ‘unicode’

cheers

jamie

So the problem is that cmds.circle(n=’%s’, nr=(1, 0, 0)) returns a list, and it is that list that you’re trying to do the % operation on.

Instead you’d probably want to do:


newCtrl = cmds.circle(n='%s' % (CTRL + name) , nr=(1, 0, 0)) 

This way you’re acting directly on the string, and not on the return value from cmds.circle()

Though really the cleaner option would be:


name = '%s' % (CTRL + name)
# Though I prefer the .format method over the % operator, but either works.
name = '{0}'.format(CTRL + name)
newCtrl = cmds.circle(n=name, nr=(1, 0, 0)) 

Thx mate for the input… interesting point on using the .format… I had just used

newName = CTRL + name

for pre formatting… which I presume isn’t as powerful as if I use

newName = ‘{0}’.format(CTRL + name)

thanks again bro! appreciate it!

Jamie

I totally agree with this as well, and I want to add why because it may not be apparent to users as to why format would be better. Format takes any number of arguments and detects their type and does the appropriate thing when converting it to a string. This is extremely invaluable with error checking.

Also, with something like:


'{0} is a type of {1}, but {1} is not a type {0}'.format('kleenex', 'tissue')
>> kleenex is a type of tissue, but tissue is not a type kleenex

Which leads to cleaner code.

There are a ton of things you can do with format, and I would strongly suggest reading the pydocs on it and testing out the different functionality.

I probably should have remembered to throw this link in: Python docs on string formatting
And honestly an easier to understand version: Python string format cookbook

The range of options that you get from str.format is downright impressive.

[QUOTE=R.White;27378]I probably should have remembered to throw this link in: Python docs on string formatting
And honestly an easier to understand version: Python string format cookbook

The range of options that you get from str.format is downright impressive.[/QUOTE]

the format as function was clever :slight_smile: