[Python] How can I correctly detect the character display width of a string in a shell script?

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    is is a character detection written using ${#text}. The upper part is the content, and the lower part is the terminal output.

    [​IMG]

    text="這是size"
    echo "$text"
    text_width=${#text}
    echo "$text_width"


    So I tried combining a Shell script with Python to calculate the text width, which correctly captures the actual character width.

    [​IMG]

    text="這是size"
    echo "$text"
    text_width=$(python3 -c "from wcwidth import wcswidth; print(wcswidth('$text'))")
    echo "$text_width"


    However, this leads to a double-escaping problem. for example, when I input z\\, the Shell escapes it once, and then Python escapes it again. Although this method accurately handles Chinese characters occupying two character widths, users need to enter \\\\ in order to output a single backslash \.

    This requires entering, but since both Shell and Python perform escaping, you end up needing to input \\ just to get a single

    [​IMG]

    I've tried many different approaches, but as a beginner, I haven't been able to make it work yet. Currently, the script blocks any input that contains special characters like backslashes or quotation marks.

    Continue reading...

Compartilhe esta Página