Markdown lines count

Hi! I am working on building two customized st.markdown-s with defined height, width, and background color. The height of these two st.markdown-s should be the same and equal to the height of the longest markdown (for example: if the first markdown has 10 lines and the second - 7, the height of these two markdowns should correspond to 10 lines.)
Markdown example:

st.markdown(
    f"""
    <div style="background-color:#e7efe0;margin: 10px; padding:10px;border-radius:10px; height:{max lines count}em; width: 35em; margin:0 auto">
        <p style="color:#333333;text-align:left;font-size:12px;">Text here</h3>
    </div>
    """,
    unsafe_allow_html=True
)

My algorithm (it is working not accurately):
I tried to calculate the lines count by approximating the number of characters one line can fit . For example, a line can fit max 30 characters, we wrap the text when the number of characters exceed this limit.
My function’s code:

def count_lines(sentence, max_num=22):
    for word in words:
        word_length = len(word)
        if current_line_length == 0:
            current_line_length += word_length
        elif current_line_length + 1 + word_length <= max_num:
            current_line_length += 1 + word_length
        else:
            lines += 1
            current_line_length = word_length
    return lines

However, each character has its own width: for instance, the width of β€œ,” and letter β€œm” is different.
I am trying to find a more efficient solution, some function that can determine the pixel count of a string. If the string has more pixels than the width of the markdown, then this string should be wrapped.

1 Like