Jason94
Jason94

Reputation: 13610

Need help converting a expression in python to C#

Maybe someone in either of the camps can tell me whats going on here:

Python:

temp = int('%d%d' % (temp2, temp3)) / 10.0;

I'm working on parsing temperature data, and found a piece of python that I can't understand. What is going on here? Is python adding together two numbers here and casting them to int, and then divide by 10?

C# might look like:

temp = ((int)(temp2+temp3))/10;

But I am not sure what that % does? Data is jibberish so I don't know what is correct translation for that line in python to C#

Upvotes: 0

Views: 81

Answers (2)

user1666620
user1666620

Reputation: 4808

this is similar: What's the difference between %s and %d in Python string formatting?

name = 'marcog'
number = 42
print '%s %d' % (name, number)

will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).

See http://docs.python.org/library/stdtypes.html#string-formatting-operations for details.

So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.

from the documentation linked in the answer I quoted:

Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.

Would probably want to set up a python script and try it out, placing your own values into the variables.

Upvotes: 0

Pavel G
Pavel G

Reputation: 26

In C# it looks like:

var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;

or:

var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;

Upvotes: 1

Related Questions