Trying to use a string variable in serial .write in Python
<p>I am communicating with a power supply through rs232. I can communicate no problem when I send for example:</p>

<pre><code>port.write("\x31")
</code></pre>

<p>but if instead I have a string as a variable</p>

<pre><code>teststring='"\\x31"'     
</code></pre>

<p>(which prints out as "\x31")</p>

<p>and I try:</p>

<pre><code>port.write(teststring)
</code></pre>

<p>it does not send the command to the supply. I have tried:</p>

<pre><code>port.write(bytes(teststring,'utf-8'))
</code></pre>

<p>and </p>

<pre><code>port.write(teststring.encode('utf-8'))
</code></pre>

<p>But it still is somehow not sending the same as just entering the text. I need to be able to change this variable, so I cannot just code the text in. 
Any help is appreciated!</p>

<p>Using comments below, I am now using an integer</p>

<p>testint=31
and if I print </p>

<p>chr(testint) I get a an odd box with 00 in the top row and 1F in the bottom. What I now need to be able to do is convert the 31 to 0x31, so I can use chr(0x31) which when printed produces 1. Hopefully the .write command will treat chr(0x31) the same as "\x31" ?</p>

<p><code>teststring</code> in your example is escaping the backslash; you have <code>"\\x30"</code>, instead of <code>"\x30"</code>. <code>"\x30"</code> is a length-1 string containing the byte 0x30; <code>"\\x30"</code> is a length-4 string containing the characters <code>\</code>, <code>x</code>, <code>3</code> and <code>0</code>. Dropping the first slash in <code>teststring</code> should behave exactly like using <code>port.write("\x30")</code>.</p>

python