Is it possible to display special characters such as space, tab etc. when printing a string?
One way to do this would be to have a dictionary of replacements for each of the characters you wanted to replace.
rep_dict = {' ': '\s', '\n': '\\n', '\t': '\\t'}
The the following function will perform the necessary replacement:
def quote(s):
return "".join(repr_dict.get(c, c) for c in s)
The repr_dict.get
call tries to look up the character in the dictionary, and uses the character itself as the default value for failed lookups.
Print special characters in list in Python
If possible, switch to Python 3 and you'll get the expected result.
If you have to make it work in Python 2, then use unicode
strings:
my_list = [u'éléphant', u'Hello World']
The way you have it right now, Python is interpreting the first string as a series of bytes with values '\xc3\xa9l\xc3\xa9phant'
which will only be converted to Unicode code points after properly UTF-8 decoded: '\xc3\xa9l\xc3\xa9phant'.decode('utf8') == u'\xe9l\xe9phant'
.
If you wish to print list repr
and get "unicode" out, you'll have to manually encode it as UTF-8 (if that's what your terminal understands).
>>> print repr(my_list).decode('unicode-escape').encode('utf8')
[u'éléphant', u'Hello World']
But it's easier to format it manually:
>>> print ", ".join(my_list)
éléphant, Hello World
How to print special characters explicitly in C?
There is no built-in mechanism to do this. You have to do it manually, character-by-character. However, the functions in ctype.h
may help. Specifically, in the "C" locale, the function isprint
is guaranteed to be true for all of the graphic characters in the basic execution character set, which is effectively the same as all the graphic characters in 7-bit ASCII, plus space; and it is guaranteed not to be true for all the control characters in 7-bit ASCII, which includes tab, carriage return, etc.
Here is a sketch:
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
int x;
setlocale(LC_ALL, "C"); // (1)
while ((x = getchar()) != EOF)
{
unsigned int c = (unsigned int)(unsigned char)x; // (2)
if (isprint(c) && c != '\\')
putchar(c);
else
printf("\\x%02x", c);
}
return 0;
}
This does not escape '
nor "
, but it does escape \
, and it is straightforward to extend that if you need it to.
Printing \n
for U+000A, \r
for U+000D, etc. is left as an exercise. Dealing with characters outside the basic execution character set (e.g. UTF-8 encoding of U+0080 through U+10FFFF) is also left as an exercise.
This program contains two things which are not necessary with a fully standards-compliant C library, but in my experience have been necessary on real operating systems. They are marked with (1)
and (2)
.
1) This explicitly sets the 'locale' configuration the way it is supposed to be set by default.
2) The value returned from getchar
is an int
. It is supposed to be either a number in the range representable by unsigned char
(normally 0-255 inclusive), or the special value EOF
(which is not in the range representable by unsigned char
). However, buggy C libraries have been known to return negative numbers for characters with their highest bit set. If that happens, the printf
will print (for instance) \xffffffa1
when it should've printed \xa1
. Casting x
to unsigned char
and then back to unsigned int
corrects this.
How can I handle these weird special characters messing my print formatting?
I've written custom string formatter based on @snakecharmerb`s comment but still "half character width" problem persist:
import unicodedata
def fstring(string, max_length, align='l'):
string = str(string)
extra_length = 0
for char in string:
if unicodedata.east_asian_width(char) == 'F':
extra_length += 1
diff = max_length - len(string) - extra_length
if diff > 0:
return string + diff * ' ' if align == 'l' else diff * ' ' + string
elif diff < 0:
return string[:max_length-3] + '.. '
return string
data = [{'user_name': 'shroud', 'game_id': 'Apex Legends', 'title': 'pathfinder twitch prime loot YAYA @shroud on socials for update', 'viewer_count': 66200},
{'user_name': 'Amouranth', 'game_id': 'ASMR', 'title': ' ( ) ✨ LIVE SUBS GET SNAPCHAT', 'viewer_count': 2261}]
for d in data:
name = fstring(d['user_name'], 20)
game_id = fstring(d['game_id'], 15)
title = fstring(d['title'], 62)
count = fstring(d['viewer_count'], 10, align='r')
print('{}{}{}{}'.format(name, game_id, title, count))
It produces output:
(can't post it as a text since formatting will be lost)
How to print special characters in a loop?
The +
operator doesn't work the way you think it does. @
is converted to it's ASCII value (64) then you add row
. When row
is 2
, you are saying: print the character that coresponds the number (64 + 2) which is A
.
Here's an ASCII Table
I would change the inside loop to something like this:
for(int ch = row; ch < CHARS; ch++) {
printf("%c", '@');
}
printf("\n");
Related Topics
How to Get the Nth Element of a Python List or a Default If Not Available
Exif Manipulation Library for Python
Too Many Different Python Versions on My System and Causing Problems
Download Image with Selenium Python
Python Extending with - Using Super() Python 3 VS Python 2
Plot a Histogram Such That Bar Heights Sum to 1 (Probability)
How to Dynamically Add/Remove Periodic Tasks to Celery (Celerybeat)
Matplotlib Legend Markers Only Once
Pandas Dataframe Concat VS Append
A Fast Way to Find the Largest N Elements in an Numpy Array
Python Accessing Nested JSON Data
Pipe Subprocess Standard Output to a Variable