Python Forum
string conversion like in source code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: string conversion like in source code (/thread-6476.html)



string conversion like in source code - Skaperen - Nov-25-2017

in Python source code, strings can be written with certain backslash codes like 'foo\nbar' will have a len() of 7 and print with 'foo' and 'bar' split to separate lines.  ord('foo\nbar'[3]) and ord('\n') will both be 10.

what i would like to know is how to do the same conversions as the Python interpreter will do when processing strings like that in source code, such as if you Python code needs to read in some Python source code an do the same with a string it gets.  also, how would you do the reverse, such as the need to convert a string with things like a newline and a carriage return in them, to a string ready to be placed between quotes and output as part of some Python source?

i can already think of ways to do this.  but i am wanting to know how you would do it.  i would like to see what is the most pythonic way or if there is a function in some module that will just do it.  code that can handle bytes and bytearray, working under python3, would be even better.  bode that can do all under both python2 and python3 would be best.


RE: string conversion like in source code - heiner55 - Nov-25-2017

You could use the six package:
http://six.readthedocs.io/#binary-and-text-data


RE: string conversion like in source code - Skaperen - Nov-25-2017

(Nov-25-2017, 05:46 AM)heiner55 Wrote: You could use the six package:
http://six.readthedocs.io/#binary-and-text-data

looking through the documentation, i don't see which function(s) to use for this.

(Nov-25-2017, 05:46 AM)heiner55 Wrote: You could use the six package:
http://six.readthedocs.io/#binary-and-text-data

i am guessing you meant this for my "string conversion like in source code" thread and accidentally posted it here.  if posting here was indented because it has something for this, could you narrow down what it is?


RE: string conversion like in source code - heiner55 - Nov-25-2017

Opps, you are right.


RE: string conversion like in source code - Skaperen - Nov-26-2017

and my oops, too.  i meant to say "chr() for bytes" to refer to the other thread.  this thread is "string conversion like in source code"