Find out the apparent width of a string in python

I wrote it because I wanted to align it vertically with a monospaced font.

Try full-width judgment with character code

# -*- coding: utf-8 -*-

def width(s):
    return sum([_width(c) for c in s.decode('utf-8')])

def _width(c):
    return 2 if _isMultiByte(c) else 1

def _isMultiByte(c):
    return ord(c) > 255

Operation check

assert 0 == width('')

assert 1 == width('a')
assert 1 == width('A')
assert 1 == width('A')
assert 1 == width('-')
assert 1 == width('+')
assert 1 == width(' ')
assert 1 == width('\\')
assert 1 == width('\n')
assert 1 == width('\t')

assert 2 == width('aa')
assert 2 == width('AA')
assert 2 == width('But')
assert 2 == width('Tsu')
assert 2 == width('Po')
assert 2 == width('I')
assert 2 == width('!')
assert 2 == width('G')
assert 2 == width('A')
assert 2 == width('○')
assert 2 == width('■')
assert 2 == width('、')
assert 2 == width('。')
assert 2 == width('‐')
assert 2 == width('-')
assert 2 == width(' ')
assert 2 == width('\\\\')
assert 2 == width('\r\n')

assert 4 == width('YY')
assert 4 == width('0w0')
assert 4 == width('OK!')

Only A is strange ... It is judged to be full-width ...

[East Asian Width](https://ja.wikipedia.org/wiki/%E6%9D%B1%E3%82%A2%E3%82%B8%E3%82%A2%E3%81%AE%E6 % 96% 87% E5% AD% 97% E5% B9% 85)

Correct only _isMultiByte

# -*- coding: utf-8 -*-

def width(s):
    return sum([_width(c) for c in s.decode('utf-8')])

def _width(c):
    return 2 if _isMultiByte(c) else 1

def _isMultiByte(c):
    import unicodedata
    return unicodedata.east_asian_width(c) in ['F', 'W', 'A']

This time everything is fine! Does this look good?

Supplement

I'm assuming standard input

$echo Howa| python width.py
8

width.py


# -*- coding: utf-8 -*-

import sys
s = sys.stdin.readlines()[0].strip()

print width(s)

Command line arguments

$ python width.py howa
8

width.py


# -*- coding: utf-8 -*-

import sys
s = sys.argv[1]

print width(s)

Also, Greek letters and Arabic letters are not covered by the operation guarantee.

Recommended Posts

Find out the apparent width of a string in python
Python --Find out number of groups in the regex expression
Find the eigenvalues of a real symmetric matrix in Python
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
Get the caller of a function in Python
Make a copy of the list in Python
Find the number of days in a month
Find the divisor of the value entered in python
Find the solution of the nth-order equation in python
Output in the form of a python array
[Python] Find the transposed matrix in a comprehension
Put out a shortened URL string in Python
Find the difference in Python
Check if the string is a number in python
Find out the location of Python class definition files.
Cut a part of the string using a Python slice
A reminder about the implementation of recommendations in Python
Maya | Find out the number of polygons in the selected object
Get the number of specific elements in a python list
[Note] Import of a file in the parent directory in Python
Find out the maximum number of characters in multi-line text stored in a data frame
I used Python to find out about the role choices of the 51 "Yachts" in the world.
Find out how many each character is in the string.
Create a random string in Python
How to quickly count the frequency of appearance of characters from a character string in Python?
Specify the encoding of the unicode string in the Python 2.x print statement
Create an instance of a predefined class from a string in Python
How to determine the existence of a selenium element in Python
How to check the memory size of a variable in Python
Read the standard output of a subprocess line by line in Python
How to check the memory size of a dictionary in Python
A function that measures the processing time of a method in python
Find the rank of a matrix in the XOR world (rank of a matrix on F2)
Get the formula in an excel file as a string in Python
[Python] A simple function to find the center coordinates of a circle
Get the number of readers of a treatise on Mendeley in Python
Conversion of string <-> date (date, datetime) in Python
Check the behavior of destructor in Python
Write the test in a python docstring
Display a list of alphabets in Python 3
Cut out A4 print in the image
Run the Python interpreter in a script
The result of installing python in Anaconda
[python] [meta] Is the type of python a type?
The basics of running NoxPlayer in Python
Generate a class from a string in Python
In search of the fastest FizzBuzz in Python
The story of blackjack A processing (python)
A memorandum of python string deletion process
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
Get a capture of the entire web page in Selenium Python VBA
If you want a singleton in python, think of the module as a singleton
Check the in-memory bytes of a floating point number float in Python
Test & Debug Tips: Create a file of the specified size in Python
I want to batch convert the result of "string" .split () in Python
I want to color a part of an Excel string in Python
Receive a list of the results of parallel processing in Python with starmap
The eval () function that calculates a string as an expression in python
Find out the name of the method that called it from the method that is python
[Introduction to Python] Thorough explanation of the character string type used in Python!
Get a datetime instance at any time of the day in Python