What Is String Formatting?

What are the main purposes of string formatting in Maya Python ?
Can you give simple examples as well ?

got a example of what you mean, are you talking about the .format method on strings or string interpolation?

name = "passerby"
age = 32

# String interpolation example
msg = f"hello i am {name} my age is {age}"
print(msg)

# formatting example
msg2 = "hello i am {} my age is {}".format(name, age)
print(msg2)

its purpose is just easily letting you create strings, that have variable inside of them.

Thank you, very helpful !!!

Is this the Chris Cunninham that grew up in Alamo CA ??

Its a pretty common name, I’m Canadian grew up in Nova Scotia.

String formatting is super-useful for combining node names:

for node in some_node_list:
  for attr in attr_list:
    cmds.setAttr("{}.{}".format(node, attr), 0)
    # in python 3: cmds.setAttr(f"{node}.{attr}", 0)

Thanks katz. So, in this example you are combining a
node name and an attr name ? explain to me why you
would want to do this ?

just in this example, imagine you have a function that takes a list of nodes (“node_list”) and you want to set specific attributes of these nodes to a specific value.

def set_node_values(node_list, attr_list, value):
    for node in node_list:
        for attr in attr_list:
            cmds.setAttr("{}.{}".format(node, attr), value)

if there are 100 nodes, and 30 attributes, you can loop through them like shown. There might be better ways to achieve this, this is just an example.

there are other ways of achieving the same result, like string concatenation:

cmds.setAttr( (node + "." + attr), 0)

and python’s str.join

cmds.setAttr(".".join(node, attr), 0)

Another unrelated neat thing you can do with string formatting is clamping float values.

x = 100.0 / 3
print(x)

output:
33.3333333333

setting the float output to have only 2 places after the decimal:

print("{:.2f}".format(x))

output:
33.33

see 5. Built-in Types — Python 2.7.18 documentation