Coder
Coder

Reputation: 91

Finding the width of the emoji using python3

I tried to print the letter "A" using patterns in python

def printA(length,height,symbol):
    a = [[" " for i in range(length)] for i in range(height)]
    for i in range(height):
        for j in range(length):
            if j == 0 or i == 0 or i == height // 2 or j == length - 1:a[i][j] = symbol
    return a

It works for normal characters like *,/+,-,#,$,% .. etc.,

Output: Normal Characters

#######
#     #
#     #
#######
#     #
#     #
#     #

Emoji

😀😀😀😀😀😀😀
😀     😀
😀     😀
😀😀😀😀😀😀😀
😀     😀
😀     😀
😀     😀

if i can find the length of the emoji , then i will be able to change the spaces to the length of the emoji so this problem won't occur, is there any way to do this

Note : The above code works only for characters and not strings

EDIT :
As of snakecharmerb's answer it works for printing just the character A but when i try to print sequnces of A i.e more than once it just misplacing the emojis

Example : I tried to print AAAAA

Output :

From the above output as we increase the letter's position it gets repositioning itself is there any way to prevent this from occuring

I printed the AAAAA like this

a = printA(7,7,"😀")
for i in a:
    for k in range(5):print(*(i),end="  ")
    print()

Upvotes: 9

Views: 1989

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55629

What matters is the width of the glyph in the font that displays the character, rather then the length of the character as a Python string. This information isn't available to Python but we can guess based on whether the symbol is a wide East Asian character, as defined by the unicode standard as reported by the unicodedata module.

import unicodedata 


def printA(length, height, symbol):  
    # Two spaces for "wide" characters, one space for others.
    spacer = '  ' if unicodedata.east_asian_width(symbol) == 'W' else ' ' 
    a = [[spacer for i in range(length)] for i in range(height)]  
    for i in range(height): 
        for j in range(length): 
            if j == 0 or i == 0 or i == height // 2 or j == length - 1:
                a[i][j] = symbol  
    return a

Using the East Asian Width property works because

emoji characters were first developed through the use of extensions of legacy East Asian encodings, such as Shift-JIS, and in such a context they were treated as wide characters. While these extensions have been added to Unicode or mapped to standardized variation sequences, their treatment as wide characters has been retained, and extended for consistency with emoji characters that lack a legacy encoding.

(link)

You may also need to check that your terminal uses a monospaced font.

See also this Q&A for some issues around aligning text with varying character width properties in a terminal, as well as this and this.

Upvotes: 11

Related Questions