I have a list of tuples in 'tups' and have applied the following code to filter. The list of tuples have the format [(floata,stra1,stra2),(floatb,strb1,strb2),...etc]
keys=sorted({t[2] for t in tups})
for key in keys:
group=filter(lambda t: t[2]==key,tups)
print '{}:\n\tmax: {}\n\tmin: {}'.format(key,max(group),min(group))
Initially I thought the curly brackets was a mistake and changed them to square brackets. I did not get a syntax error but the code did not work. As a last resort I changed the brackets back and everything was fine. Can someone explain the construction. Is this a dictionary comprehension? Where is this explained in the documentation?
If you mean the curly brackets in the first line, this is a set comprehension. This will create a set of the third item from every tuple in tups. A set is similar to a list, but without order, and therefore cannot contain duplicates.
If you mean the brackets in the string, this is just new-style string formatting. Calling str.format() changes those braces into the passed values.
Before Python 2.6, you would have used:
print '%s:\n\tmax: %s\n\tmin: %s' % (key,max(group),min(group))
to format a string using placeholders (the %s).
Since Python 2.6, you can use the {} syntax for the placeholder and .format instead:
print '{}:\n\tmax: {}\n\tmin: {}'.format(key,max(group),min(group))
or using positional arguments:
print '{0}:\n\tmax: {2}\n\tmin: {1}'.format(key,min(group),max(group))
(notice that I changed the order of the arguments, but the output is the same: we used {2} to represent the third argument...)
Just an advice: when you get a lot of arguments, it's easier to name them, as:
print '{key}:\n\tmax: {groupmax}\n\tmin: {groupmin}'.format(key=key,groupmin=min(group),groupmax=max(group))
The .format syntax is more powerful than the % one: examples are available in the documentation.
Related
I would like to put an int into a string. This is what I am doing at the moment:
num = 40
plot.savefig('hanning40.pdf') #problem line
I have to run the program for several different numbers, so I'd like to do a loop. But inserting the variable like this doesn't work:
plot.savefig('hanning', num, '.pdf')
How do I insert a variable into a Python string?
See also
If you tried using + to concatenate a number with a string (or between strings, etc.) and got an error message, see How can I concatenate str and int objects?.
If you are trying to assemble a URL with variable data, do not use ordinary string formatting, because it is error-prone and more difficult than necessary. Specialized tools are available. See Add params to given URL in Python.
If you are trying to assemble a SQL query, do not use ordinary string formatting, because it is a major security risk. This is the cause of "SQL injection" which costs real companies huge amounts of money every year. See for example Python: best practice and securest way to connect to MySQL and execute queries for proper techniques.
If you just want to print (output) the string, you can prepare it this way first, or if you don't need the string for anything else, print each piece of the output individually using a single call to print. See How can I print multiple things (fixed text and/or variable values) on the same line, all at once? for details on both approaches.
Using f-strings:
plot.savefig(f'hanning{num}.pdf')
This was added in 3.6 and is the new preferred way.
Using str.format():
plot.savefig('hanning{0}.pdf'.format(num))
String concatenation:
plot.savefig('hanning' + str(num) + '.pdf')
Conversion Specifier:
plot.savefig('hanning%s.pdf' % num)
Using local variable names (neat trick):
plot.savefig('hanning%(num)s.pdf' % locals())
Using string.Template:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
See also:
Fancier Output Formatting - The Python Tutorial
Python 3's f-Strings: An Improved String Formatting Syntax (Guide) - RealPython
With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
With the example given in the question, it would look like this
plot.savefig(f'hanning{num}.pdf')
plot.savefig('hanning(%d).pdf' % num)
The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:
printf-style String Formatting
You can use + as the normal string concatenation function as well as str().
"hello " + str(10) + " world" == "hello 10 world"
In general, you can create strings using:
stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
If you would want to put multiple values into the string you could make use of format
nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))
Would result in the string hanning123.pdf. This can be done with any array.
Special cases
Depending on why variable data is being used with strings, the general-purpose approaches may not be appropriate.
If you need to prepare an SQL query
Do not use any of the usual techniques for assembling a string. Instead, use your SQL library's functionality for parameterized queries.
A query is code, so it should not be thought about like normal text. Using the library will make sure that any inserted text is properly escaped. If any part of the query could possibly come from outside the program in any way, that is an opportunity for a malevolent user to perform SQL injection. This is widely considered one of the important computer security problems, costing real companies huge amounts of money every year and causing problems for countless customers. Even if you think you know the data is "safe", there is no real upside to using any other approach.
The syntax will depend on the library you are using and is outside the scope of this answer.
If you need to prepare a URL query string
See Add params to given URL in Python. Do not do it yourself; there is no practical reason to make your life harder.
Writing to a file
While it's possible to prepare a string ahead of time, it may be simpler and more memory efficient to just write each piece of data with a separate .write call. Of course, non-strings will still need to be converted to string before writing, which may complicate the code. There is not a one-size-fits-all answer here, but choosing badly will generally not matter very much.
If you are simply calling print
The built-in print function accepts a variable number of arguments, and can take in any object and stringify it using str. Before trying string formatting, consider whether simply passing multiple arguments will do what you want. (You can also use the sep keyword argument to control spacing between the arguments.)
# display a filename, as an example
print('hanning', num, '.pdf', sep='')
Of course, there may be other reasons why it is useful for the program to assemble a string; so by all means do so where appropriate.
It's important to note that print is a special case. The only functions that work this way are ones that are explicitly written to work this way. For ordinary functions and methods, like input, or the savefig method of Matplotlib plots, we need to prepare a string ourselves.
Concatenation
Python supports using + between two strings, but not between strings and other types. To work around this, we need to convert other values to string explicitly: 'hanning' + str(num) + '.pdf'.
Template-based approaches
Most ways to solve the problem involve having some kind of "template" string that includes "placeholders" that show where information should be added, and then using some function or method to add the missing information.
f-strings
This is the recommended approach when possible. It looks like f'hanning{num}.pdf'. The names of variables to insert appear directly in the string. It is important to note that there is not actually such a thing as an "f-string"; it's not a separate type. Instead, Python will translate the code ahead of time:
>>> def example(num):
... return f'hanning{num}.pdf'
...
>>> import dis
>>> dis.dis(example)
2 0 LOAD_CONST 1 ('hanning')
2 LOAD_FAST 0 (num)
4 FORMAT_VALUE 0
6 LOAD_CONST 2 ('.pdf')
8 BUILD_STRING 3
10 RETURN_VALUE
Because it's a special syntax, it can access opcodes that aren't used in other approaches.
str.format
This is the recommended approach when f-strings aren't possible - mainly, because the template string needs to be prepared ahead of time and filled in later. It looks like 'hanning{}.pdf'.format(num), or 'hanning{num}.pdf'.format(num=num)'. Here, format is a method built in to strings, which can accept arguments either by position or keyword.
Particularly for str.format, it's useful to know that the built-in locals, globals and vars functions return dictionaries that map variable names to the contents of those variables. Thus, rather than something like '{a}{b}{c}'.format(a=a, b=b, c=c), we can use something like '{a}{b}{c}'.format(**locals()), unpacking the locals() dict.
str.format_map
This is a rare variation on .format. It looks like 'hanning{num}.pdf'.format_map({'num': num}). Rather than accepting keyword arguments, it accepts a single argument which is a mapping.
That probably doesn't sound very useful - after all, rather than 'hanning{num}.pdf'.format_map(my_dict), we could just as easily write 'hanning{num}.pdf'.format(**my_dict). However, this is useful for mappings that determine values on the fly, rather than ordinary dicts. In these cases, unpacking with ** might not work, because the set of keys might not be determined ahead of time; and trying to unpack keys based on the template is unwieldy (imagine: 'hanning{num}.pdf'.format(num=my_mapping[num]), with a separate argument for each placeholder).
string.Formatter
The string standard library module contains a rarely used Formatter class. Using it looks like string.Formatter().format('hanning{num}.pdf', num=num). The template string uses the same syntax again. This is obviously clunkier than just calling .format on the string; the motivation is to allow users to subclass Formatter to define a different syntax for the template string.
All of the above approaches use a common "formatting language" (although string.Formatter allows changing it); there are many other things that can be put inside the {}. Explaining how it works is beyond the scope of this answer; please consult the documentation. Do keep in mind that literal { and } characters need to be escaped by doubling them up. The syntax is presumably inspired by C#.
The % operator
This is a legacy way to solve the problem, inspired by C and C++. It has been discouraged for a long time, but is still supported. It looks like 'hanning%s.pdf' % num, for simple cases. As you'd expect, literal '%' symbols in the template need to be doubled up to escape them.
It has some issues:
It seems like the conversion specifier (the letter after the %) should match the type of whatever is being interpolated, but that's not actually the case. Instead, the value is converted to the specified type, and then to string from there. This isn't normally necessary; converting directly to string works most of the time, and converting to other types first doesn't help most of the rest of the time. So 's' is almost always used (unless you want the repr of the value, using 'r'). Despite that, the conversion specifier is a mandatory part of the syntax.
Tuples are handled specially: passing a tuple on the right-hand side is the way to provide multiple arguments. This is an ugly special case that's necessary because we aren't using function-call syntax. As a result, if you actually want to format a tuple into a single placeholder, it must be wrapped in a 1-tuple.
Other sequence types are not handled specially, and the different behaviour can be a gotcha.
string.Template
The string standard library module contains a rarely used Template class. Instances provide substitute and safe_substitute methods that work similarly to the built-in .format (safe_substitute will leave placeholders intact rather than raising an exception when the arguments don't match). This should also be considered a legacy approach to the problem.
It looks like string.Template('hanning$num.pdf').substitute(num=num), and is inspired by traditional Perl syntax. It's obviously clunkier than the .format approach, since a separate class has to be used before the method is available. Braces ({}) can be used optionally around the name of the variable, to avoid ambiguity. Similarly to the other methods, literal '$' in the template needs to be doubled up for escaping.
I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:
['file' + str(i) + '.pdf' for i in range(1,4)]
You can make dict and substitute variables in your string.
var = {"name": "Abdul Jalil", "age": 22}
temp_string = "My name is %(name)s. I am %(age)s years old." % var
Could someone please break down why "{dic['string_key']}".format(dic=dic) considers the single quotations to be part of the string-key and does a lookup under dic["'string_key'"] ?
a) and b) show the correct way, however I am missing the reason.
a = "{dic[string_key]}"
print(a.format(dic=dic))
b = f"{dic['string_key']}"
print(b)
format and f-strings use braces differently.
With str.format, the contents of the braces are part of a mini-language used by format to substitute its arguments into the format string.
In an f-string, it's an arbitrary Python expression to evaluate.
In this case:
a = "{dic[string_key]}"
print(a.format(dic=dic))
... the string is formatted when .format() is called and that function uses a formatting language that is documented here https://docs.python.org/3/library/string.html#formatstrings.
But in this case:
b = f"{dic['string_key']}"
print(b)
... the string is formatted when the assignment to b is executed, by Python itself. The expression inside the f-string follows normal Python syntax, with the exception that you cannot reuse the quotes used to enclose the f-string.
As a result, you need to specify the quotes around the dictionary key as you would normally, while the mini-language for .format() expects you to omit them.
Also note that this makes a lot of sense: b = f"{dic[string_key]}" should use the value of the variable string_key to index the dictionary.
I would like to put an int into a string. This is what I am doing at the moment:
num = 40
plot.savefig('hanning40.pdf') #problem line
I have to run the program for several different numbers, so I'd like to do a loop. But inserting the variable like this doesn't work:
plot.savefig('hanning', num, '.pdf')
How do I insert a variable into a Python string?
See also
If you tried using + to concatenate a number with a string (or between strings, etc.) and got an error message, see How can I concatenate str and int objects?.
If you are trying to assemble a URL with variable data, do not use ordinary string formatting, because it is error-prone and more difficult than necessary. Specialized tools are available. See Add params to given URL in Python.
If you are trying to assemble a SQL query, do not use ordinary string formatting, because it is a major security risk. This is the cause of "SQL injection" which costs real companies huge amounts of money every year. See for example Python: best practice and securest way to connect to MySQL and execute queries for proper techniques.
If you just want to print (output) the string, you can prepare it this way first, or if you don't need the string for anything else, print each piece of the output individually using a single call to print. See How can I print multiple things (fixed text and/or variable values) on the same line, all at once? for details on both approaches.
Using f-strings:
plot.savefig(f'hanning{num}.pdf')
This was added in 3.6 and is the new preferred way.
Using str.format():
plot.savefig('hanning{0}.pdf'.format(num))
String concatenation:
plot.savefig('hanning' + str(num) + '.pdf')
Conversion Specifier:
plot.savefig('hanning%s.pdf' % num)
Using local variable names (neat trick):
plot.savefig('hanning%(num)s.pdf' % locals())
Using string.Template:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
See also:
Fancier Output Formatting - The Python Tutorial
Python 3's f-Strings: An Improved String Formatting Syntax (Guide) - RealPython
With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
With the example given in the question, it would look like this
plot.savefig(f'hanning{num}.pdf')
plot.savefig('hanning(%d).pdf' % num)
The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:
printf-style String Formatting
You can use + as the normal string concatenation function as well as str().
"hello " + str(10) + " world" == "hello 10 world"
In general, you can create strings using:
stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
If you would want to put multiple values into the string you could make use of format
nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))
Would result in the string hanning123.pdf. This can be done with any array.
Special cases
Depending on why variable data is being used with strings, the general-purpose approaches may not be appropriate.
If you need to prepare an SQL query
Do not use any of the usual techniques for assembling a string. Instead, use your SQL library's functionality for parameterized queries.
A query is code, so it should not be thought about like normal text. Using the library will make sure that any inserted text is properly escaped. If any part of the query could possibly come from outside the program in any way, that is an opportunity for a malevolent user to perform SQL injection. This is widely considered one of the important computer security problems, costing real companies huge amounts of money every year and causing problems for countless customers. Even if you think you know the data is "safe", there is no real upside to using any other approach.
The syntax will depend on the library you are using and is outside the scope of this answer.
If you need to prepare a URL query string
See Add params to given URL in Python. Do not do it yourself; there is no practical reason to make your life harder.
Writing to a file
While it's possible to prepare a string ahead of time, it may be simpler and more memory efficient to just write each piece of data with a separate .write call. Of course, non-strings will still need to be converted to string before writing, which may complicate the code. There is not a one-size-fits-all answer here, but choosing badly will generally not matter very much.
If you are simply calling print
The built-in print function accepts a variable number of arguments, and can take in any object and stringify it using str. Before trying string formatting, consider whether simply passing multiple arguments will do what you want. (You can also use the sep keyword argument to control spacing between the arguments.)
# display a filename, as an example
print('hanning', num, '.pdf', sep='')
Of course, there may be other reasons why it is useful for the program to assemble a string; so by all means do so where appropriate.
It's important to note that print is a special case. The only functions that work this way are ones that are explicitly written to work this way. For ordinary functions and methods, like input, or the savefig method of Matplotlib plots, we need to prepare a string ourselves.
Concatenation
Python supports using + between two strings, but not between strings and other types. To work around this, we need to convert other values to string explicitly: 'hanning' + str(num) + '.pdf'.
Template-based approaches
Most ways to solve the problem involve having some kind of "template" string that includes "placeholders" that show where information should be added, and then using some function or method to add the missing information.
f-strings
This is the recommended approach when possible. It looks like f'hanning{num}.pdf'. The names of variables to insert appear directly in the string. It is important to note that there is not actually such a thing as an "f-string"; it's not a separate type. Instead, Python will translate the code ahead of time:
>>> def example(num):
... return f'hanning{num}.pdf'
...
>>> import dis
>>> dis.dis(example)
2 0 LOAD_CONST 1 ('hanning')
2 LOAD_FAST 0 (num)
4 FORMAT_VALUE 0
6 LOAD_CONST 2 ('.pdf')
8 BUILD_STRING 3
10 RETURN_VALUE
Because it's a special syntax, it can access opcodes that aren't used in other approaches.
str.format
This is the recommended approach when f-strings aren't possible - mainly, because the template string needs to be prepared ahead of time and filled in later. It looks like 'hanning{}.pdf'.format(num), or 'hanning{num}.pdf'.format(num=num)'. Here, format is a method built in to strings, which can accept arguments either by position or keyword.
Particularly for str.format, it's useful to know that the built-in locals, globals and vars functions return dictionaries that map variable names to the contents of those variables. Thus, rather than something like '{a}{b}{c}'.format(a=a, b=b, c=c), we can use something like '{a}{b}{c}'.format(**locals()), unpacking the locals() dict.
str.format_map
This is a rare variation on .format. It looks like 'hanning{num}.pdf'.format_map({'num': num}). Rather than accepting keyword arguments, it accepts a single argument which is a mapping.
That probably doesn't sound very useful - after all, rather than 'hanning{num}.pdf'.format_map(my_dict), we could just as easily write 'hanning{num}.pdf'.format(**my_dict). However, this is useful for mappings that determine values on the fly, rather than ordinary dicts. In these cases, unpacking with ** might not work, because the set of keys might not be determined ahead of time; and trying to unpack keys based on the template is unwieldy (imagine: 'hanning{num}.pdf'.format(num=my_mapping[num]), with a separate argument for each placeholder).
string.Formatter
The string standard library module contains a rarely used Formatter class. Using it looks like string.Formatter().format('hanning{num}.pdf', num=num). The template string uses the same syntax again. This is obviously clunkier than just calling .format on the string; the motivation is to allow users to subclass Formatter to define a different syntax for the template string.
All of the above approaches use a common "formatting language" (although string.Formatter allows changing it); there are many other things that can be put inside the {}. Explaining how it works is beyond the scope of this answer; please consult the documentation. Do keep in mind that literal { and } characters need to be escaped by doubling them up. The syntax is presumably inspired by C#.
The % operator
This is a legacy way to solve the problem, inspired by C and C++. It has been discouraged for a long time, but is still supported. It looks like 'hanning%s.pdf' % num, for simple cases. As you'd expect, literal '%' symbols in the template need to be doubled up to escape them.
It has some issues:
It seems like the conversion specifier (the letter after the %) should match the type of whatever is being interpolated, but that's not actually the case. Instead, the value is converted to the specified type, and then to string from there. This isn't normally necessary; converting directly to string works most of the time, and converting to other types first doesn't help most of the rest of the time. So 's' is almost always used (unless you want the repr of the value, using 'r'). Despite that, the conversion specifier is a mandatory part of the syntax.
Tuples are handled specially: passing a tuple on the right-hand side is the way to provide multiple arguments. This is an ugly special case that's necessary because we aren't using function-call syntax. As a result, if you actually want to format a tuple into a single placeholder, it must be wrapped in a 1-tuple.
Other sequence types are not handled specially, and the different behaviour can be a gotcha.
string.Template
The string standard library module contains a rarely used Template class. Instances provide substitute and safe_substitute methods that work similarly to the built-in .format (safe_substitute will leave placeholders intact rather than raising an exception when the arguments don't match). This should also be considered a legacy approach to the problem.
It looks like string.Template('hanning$num.pdf').substitute(num=num), and is inspired by traditional Perl syntax. It's obviously clunkier than the .format approach, since a separate class has to be used before the method is available. Braces ({}) can be used optionally around the name of the variable, to avoid ambiguity. Similarly to the other methods, literal '$' in the template needs to be doubled up for escaping.
I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:
['file' + str(i) + '.pdf' for i in range(1,4)]
You can make dict and substitute variables in your string.
var = {"name": "Abdul Jalil", "age": 22}
temp_string = "My name is %(name)s. I am %(age)s years old." % var
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
For the following lines of Python code I'm failing to understand a key concept.
A string is assigned to the variable joke_evaluationand include {} to embed another variable within it.
The third line of code has got me stuck, we are saying print the variable joke_evaluation then using the .format() function and passing another variable to it - hilarious which is set as a boolean data type.
Are the {} effectively functioning as placeholders? How does the .format() function know to populate the {} with the variable hilarious?
Please explain in basic terms if possible to increase my understanding, I'm failing to understand how Python populates the curly braces {} as I've mentioned above.
Here's my understanding of the the format method:
Any string with curly braces {} will be replaced with the variable you have provided. So, if I have a string say:
myStr = "hello {}"
then doing:
res = myStr.format("user")
print(res) #prints "hello user" without quotes.
Now, doing this:
res = myStr.format(123123)
print(res) #prints "hello 123123" without quotes.
As you might have guessed, the integer 123123 was implicitly converted to string before being included in the string.
Now, coming to the curly {} part:
You can have multiple curly braces and must have the same number of parameters passed to format method. Eg:
myStr = "hello {},{},{}, nice meeting you"
res = myStr.format("abcd",123,"lol")
print(res) #prints "hello abcd,123,lol, nice meeting you"
You can even put indices in the {} to indicate position like {0} and {1}.
Yes, {} acting as placeholders, which is treated by .format method in special way.
How does the .format() function know to populate the {} with the variable hilarious?
If you're providing {} only, it's substituted position-wise, i.e.
>>> 'first: {}, second: {}'.format(1, 2)
'first: 1, second: 2'
For more verbose or re-usable substitution you can use named arguments:
>>> "{actor1} tells {actor2} that he's {actor1}".format(actor1='Bob', actor2='Joel')
"Bob tells Joel that he's Bob"
More on awesome string formatting: pyformat.info
A bit more on formatting, when .format substituting placeholders with some objects, it calls __format__ method on it, which
Accepts formatting spec — which gives you ability to control how it will be converted (for example, '{:.2f}'.format(3.1415)
Return str, which will actually substitute placeholders
Read Python documentation about string: https://docs.python.org/3.6/library/string.html?highlight=formatting
:) Everything you need to know. You can also change Python versions and see the behavior of formatting.
Scroll down to see examples and explanations.
The code is as below:
self.class_logg('http://example.com/api/?\
option=ajax&nologin=1&a=vmware_migrate_2&\
original_server_ip=%s&target_server_ip=%s&\
vmware_name=%s' % (self.ip, dest_node.ip, machine.name))
Because this string is so long, i have to split it into those several lines, but unfortunately find that in the log it prints like this:
http://example.com/api/?option=ajax &nologin=1&a=vmware_migrate_2 &original_server_ip=192.168.0.224$
Apparently it prints the indentation spaces there. How to resolve this problem?
the self.class_logg is just there for example, in my case the problem happens even if it is print.
You can just remove the \
self.class_logg(('http://example.com/api/?'
'option=ajax&nologin=1&a=vmware_migrate_2&'
'original_server_ip=%s&target_server_ip=%s&'
'vmware_name=%s' % (self.ip, dest_node.ip, machine.name)))
In Python, when strings are next to each other in the code, it will combine them. It is called "string grouping"
However, it seems to me that you would do better with a dictionary:
fields = {'option': 'ajax',
'nologin': '1',
'a': 'vmware_migrate_2',
'original_server_ip': self.ip,
'target_server_ip': dest_node.ip,
'vmware_name': machine.name}
params = '&'.join(['{}={}'.format(k, v) for k, v in fields.items()])
self.class_logg('http://example.com/api/?{}'.format(params))
If the order is important (which it should not be) You can use an OrderedDict, or a list of tuples.
You can make use of a handy trick that arises from how Python handles adjacent string constants:
self.class_logg('http://example.com/api/?'
'option=ajax&nologin=1&a=vmware_migrate_2&'
'original_server_ip=%s&target_server_ip=%s&'
'vmware_name=%s' % (self.ip, dest_node.ip, machine.name))
When Python sees two string constants immediately adjacent, it automatically joins them together to make a single string constant. This includes across lines, as long as Python recognizes that the next line is a continuation of the previous (which it will in this case, since you're inside a pair of parentheses).
You can see this in action with a simple example:
>>> print ('abc'
'def'
'ghi')
abcdefghi
You should use grouping instead of concatanation or any other line braking:
self.class_logg('http://example.com/api/?'
'option=ajax&nologin=1&a=vmware_migrate_2&'
'original_server_ip=%s&target_server_ip=%s&'
'vmware_name=%s' % (self.ip, dest_node.ip, machine.name))
Personal recommendation: you should use format instead of %:
self.class_logg(('http://example.com/api/?'
'option=ajax&nologin=1&a=vmware_migrate_2&'
'original_server_ip={}&target_server_ip={}&'
'vmware_name={}').format(self.ip, dest_node.ip, machine.name))
What you have here is one huge string with tabulations. Split in four different strings like so:
self.class_logg('http://example.com/api/?'\
'option=ajax&nologin=1&a=vmware_migrate_2&'\
'original_server_ip=%s&target_server_ip=%s&'\
'vmware_name=%s' % (self.ip, dest_node.ip, machine.name))
What matters are the single quotes in the start of every single string.