473,594 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

interpretation of special characters in Python

TP
Hi everybody,

I am new to Python, I try to understand how Python treats special
characters. For example, if I execute the following line in a shell
console, I obtain a colored string:

$ python -c "print '\033[30;44m foo \033[0m'"

So, it works.
Some time ago, I have made a lot of shell variables with all possible colors
(with shell functions executed each time I launch a new shell). For
example:

$ echo -e $esc$ColorBlack OnDarkblue foo $esc$ColorReset

gives the same result than the python command above.
To know the corresponding non-interpreted characters, I can use the -n
option of echo:

$ echo -n $esc$ColorBlack OnDarkblue foo $esc$ColorReset
\033[30;44m foo \033[0m

So, it is exactly the string above, as expected.

My problem arises when it comes to get these shell variables ( $esc,
$ColorBlackOnDa rkblue, $ColorReset) in a Python script, with os.environ, in
the following 5-line script:

import os
Color = os.environ['ColorBlackOnDa rkblue']
ColorReset = os.environ['ColorReset']
Esc = os.environ['esc']
print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset)

Run this script color.py, but after having defined these shell variables in
a shell:

$ export esc="\033"
$ export ColorBlackOnDar kblue="[30;44m"
$ export ColorReset="[0m"

When I execute the Python script, I do not obtain any special character
interpretation in Python:

$ python color.py
\033[30;44m foo \033[0m

Why? What is the problem? Is there any solution?
I really want to get my shell color variables.

Thanks a lot

--
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
Jul 6 '08 #1
9 2564
On Sun, 06 Jul 2008 23:42:26 +0200, TP <Tr**********@P aralleles.inval idwrote:
>
$ python -c "print '\033[30;44m foo \033[0m'"
[writes an escape sequence to stdout]
$ echo -e $esc$ColorBlack OnDarkblue foo $esc$ColorReset
[also writes an escape sequence to stdout]
$ echo -n $esc$ColorBlack OnDarkblue foo $esc$ColorReset
\033[30;44m foo \033[0m
[snip, shuffle]
$ export esc="\033"
$ export ColorBlackOnDar kblue="[30;44m"
$ export ColorReset="[0m"

import os
Color = os.environ['ColorBlackOnDa rkblue']
ColorReset = os.environ['ColorReset']
Esc = os.environ['esc']
print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset)
[snip]
$ python color.py
\033[30;44m foo \033[0m
The string "\033" is 4 characters long. Your shell variable
"esc" is 4 characters long. Your Python program prints
those four characters. You want it to re-interpret those 4
characters into a single escape character.

One of this group's regular participants can (I hope) tell
us three breathtakingly elegant ways to do that. I'm sorry
I can't.

When you run echo, it recognizes the 4-character "esc" as a
convention for representing a single character, and performs
the re-interpretation for you. When you tell python
"print '\033[30;44m foo \033[0m'", python interprets
the "\033" as a single character.

--
To email me, substitute nowhere->spamcop, invalid->net.
Jul 7 '08 #2
TP
Dennis Lee Bieber wrote:
Off-hand, I'd probably try first with:

csi = "\033["

and then define your

colorblackondar kblue = $csi"30;44m"
Thanks for your answer.
I have tried this slight modification, but it does not change anything on my
terminal.
--
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
Jul 7 '08 #3
TP
Peter Pearson wrote:

Thanks for your answer.
When you run echo, it recognizes the 4-character "esc" as a
convention for representing a single character, and performs
the re-interpretation for you. When you tell python
"print '\033[30;44m foo \033[0m'", python interprets
the "\033" as a single character.
So, the python print command *can* interpret these 4-character as a single
character. It would be odd if there were no possibility to do the same
thing when the characters are (i) stored in a python variable, or (ii) come
from the environment variables. Does anybody know any way to re-interpret a
string in Python? I have tried to play with "eval" (as in bash), but it
does not yield anything.

--
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
Jul 7 '08 #4
TP <Tr**********@P aralleles.inval idwrites:
Peter Pearson wrote:
When you tell python "print '\033[30;44m foo \033[0m'", python
interprets the "\033" as a single character.

So, the python print command *can* interpret these 4-character as a
single character.
Not "interpret" , no.

It's more accurate to say that the Python *compiler* will translate
"\033" within a string literal into a single character in the compiled
executable byte code.

That is, the input to the Python interpreter will not have "\033" in
the string literal at all, but instead a single character produced by
the Python compiler at that point in the byte code.
It would be odd if there were no possibility to do the same thing
when the characters are (i) stored in a python variable, or (ii)
come from the environment variables.
Since those are not the input to the Python compiler, they can't be
translated this way.

--
\ “You know I could rent you out as a decoy for duck hunters?†|
`\ —Groucho Marx |
_o__) |
Ben Finney
Jul 7 '08 #5
TP
TP wrote:
So, the python print command *can* interpret these 4-character as a single
character. It would be odd if there were no possibility to do the same
thing when the characters are (i) stored in a python variable
Sorry, it works when using variables. Try for example:

col="[0;31m"
esc="\033"
colreset="[0m"
print esc + col + "foobar" + esc + colreset

--
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
Jul 7 '08 #6
Peter Pearson wrote:
On Sun, 06 Jul 2008 23:42:26 +0200, TP <Tr**********@P aralleles.inval id>
wrote:
>>
$ python -c "print '\033[30;44m foo \033[0m'"
[writes an escape sequence to stdout]
>$ echo -e $esc$ColorBlack OnDarkblue foo $esc$ColorReset
[also writes an escape sequence to stdout]
>$ echo -n $esc$ColorBlack OnDarkblue foo $esc$ColorReset
\033[30;44m foo \033[0m

[snip, shuffle]
>$ export esc="\033"
$ export ColorBlackOnDar kblue="[30;44m"
$ export ColorReset="[0m"

import os
Color = os.environ['ColorBlackOnDa rkblue']
ColorReset = os.environ['ColorReset']
Esc = os.environ['esc']
print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset)
[snip]
>$ python color.py
\033[30;44m foo \033[0m

The string "\033" is 4 characters long. Your shell variable
"esc" is 4 characters long. Your Python program prints
those four characters. You want it to re-interpret those 4
characters into a single escape character.

One of this group's regular participants can (I hope) tell
us three breathtakingly elegant ways to do that. I'm sorry
I can't.

When you run echo, it recognizes the 4-character "esc" as a
convention for representing a single character, and performs
the re-interpretation for you. When you tell python
"print '\033[30;44m foo \033[0m'", python interprets
the "\033" as a single character.
Peter Pearson's explanation is spot-on. You get the 4-character sequence
instead of the escape code chr(27).

$ export esc="\033"
$ python
Python 2.5.1 (r251:54863, Mar 7 2008, 03:39:23)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
>>import os
os.environ["esc"]
'\\033'
>>print _
\033

If you want to interpret "\\033" as "\033" you have to perform the
conversion explicitly. Fortunately there already is an encoding that
understands these escape sequences for characters:
>>esc = os.environ["esc"].decode("string-escape")
esc
'\x1b'
>>print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc)
alles so schoen bunt hier

Peter
Jul 7 '08 #7
TP
Peter Otten wrote:
>>>esc = os.environ["esc"].decode("string-escape")
esc
'\x1b'
>>>print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc)
alles so schoen bunt hier
Thanks a lot for your help. It works perfectly.
Indeed, one can read in the documentation concerning encodings:

"Produce a string that is suitable as string literal in Python source code"

--
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
Jul 7 '08 #8
On Mon, 07 Jul 2008 10:05:56 +0200, TP <Tr**********@P aralleles.inval idwrote:
TP wrote:
>So, the python print command *can* interpret these 4-character as a single
character. It would be odd if there were no possibility to do the same
thing when the characters are (i) stored in a python variable

Sorry, it works when using variables. Try for example:

col="[0;31m"
esc="\033"
colreset="[0m"
print esc + col + "foobar" + esc + colreset
I don't understand exactly what you mean by "Sorry", but
let me direct your attention to the fact that the "interpretation "
step about which we're talking happens during the parsing
of the string literal (i.e., while the statement esc="\033" is
processed), not during the execution of the print statement.
To prove this assertion, simply print len(esc). You will see
that esc is a single character long.

--
To email me, substitute nowhere->spamcop, invalid->net.
Jul 8 '08 #9
TP
Peter Pearson wrote:
I don't understand exactly what you mean by "Sorry"
I means: please forgive me for having said that it does not work with
variables, because it is completely false.

Thanks one more time

Julien

--
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
Jul 8 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
9894
by: Gregor | last post by:
I am trying to print some special characters, but they come out as different characters in the Python console. If I have a script like this: # -*- coding: latin_1 -*- print "Mädchen" print "M\xE4dchen" Both statements produce a capital sigma where they ä should be. Typing "\xE4" directly in the console also spits back a sigma.
1
2424
by: ulrice jardin | last post by:
hi I had a look to this htmlentitydefs lib, but I still don't know how to convert html special characters into latin-1 characters. For instance, how can I convert ' into ' or é and &eacute; into é? Is there any function to do that? thx for any help
3
2190
by: trapeze.jsg | last post by:
Hi. Platform: Win XP Python version: 2.4.1 Running script from: cmd.exe (windows console) I am having some trouble passing arguments to a python script having special characters. In my case the argument is a filename (eg. udtræk.xml). It seems like python tries to guess the encoding in which the arguments are passed, instead of just recieving them in unicode,
3
1448
by: Scott David Daniels | last post by:
In reading over the source for CPython's PyUnicode_EncodeDecimal, I see a dance to handle characters which are neither dec-equiv nor in Latin-1. Does anyone know about the intent of such a conversion? As far as I can tell, error handling is one of: strict, replace, ignore, xmlcharrefreplace, or something_else What I don't understand is whether, in the ignore or something_else cases, there is any chance that digits will show up anywhere...
0
1516
by: Luis Corrales | last post by:
Hi all, I have a problem when searching for text with special characters in e-mails in an IMAP server. I'm using imaplib in python 2.4.3 and I can't get this code working: # first connect and login conn = IMAP4(my_server) conn.login(my_user, my_pass)
1
4558
by: sonald | last post by:
Dear All, I am working on a module that validates the provided CSV data in a text format, which must be in a predefined format. We check for the : 1. Number of fields provided in the text file, 2. Text checks for max. length of the field & whether the field is mandatory or optional Example:
1
3022
by: ronrsr | last post by:
I have an MySQL database called zingers. The structure is: zid - integer, key, autoincrement keyword - varchar citation - text quotation - text I am having trouble storing text, as typed in latter two fields. Special characters and punctuation all seem not to be stored and retrieved correctly.
1
1764
by: ronrsr | last post by:
I have an MySQL database called zingers. The structure is: zid - integer, key, autoincrement keyword - varchar citation - text quotation - text I am having trouble storing text, as typed in latter two fields. Special characters and punctuation all seem not to be stored and retrieved correctly.
3
10189
KevinADC
by: KevinADC | last post by:
Purpose The purpose of this article is to discuss the difference between characters inside a character class and outside a character class and some special characters inside a character class. This is not a regular expression tutorial. Assumes you are already familiar with basic regular expression concepts and terminology. If not, you may want to read some regular expression tutorial. See the end of the article for links to online resources....
0
7947
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7880
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8255
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8010
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8242
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5739
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3868
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1486
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.