I’ve been messing around with Python over the past couple of days. After all of the languages with a C-like or BASIC-like syntax, Python is a step apart.
If you remember the string format specifier in C with printf/sprintf/fprintf and the String.Format in C#, you are going to love the Python string.format because of how flexible it is. Let me walk you through it.
First, we start off by defining a string like so:
s = ‘This is {name}’
Now, all we want to do is replace ‘name’ with a string using this:
s = s.format(name=’Nitin’)
Finally, print the string using:
print(s)
If you prefer to have the string.format use positional parameters, you can still do this:
s = ‘This is {0} (I repeat, this is {0}) and this is {1}’
And then do a
s = s.format(‘one’, ‘two’)
If you don’t need to repeat any of the parameters, you can leave out the numbers and do a
‘This is {} and this is {}’.format(1,2)
You can also refer to specific member variables or array elements using something like ‘{thearray[3]}’ and ‘{0.email} ‘
You can read more about the string.format method on the Python string documentation page.
No comments yet.