St.code() adds a tab to code automatically start from the second line in a tab container

I’'m using st.code() inside a tab container, but the showed code will be added a tab before each line start from the second line, any way I can remove it it to let the codes aligned?

Codes for reproduce:

import streamlit as st

st.code('''
import streamlit as st

st.write("Hello, Streamlit!")
st.write("Hello, Streamlit!")
''', 
'python')

tab1, tab2 = st.tabs(["Cat", "Dog"])
with tab1:
    st.code('''
    import streamlit as st

    st.write("Hello, Streamlit!")
    st.write("Hello, Streamlit!")
    ''', 
    'python')

This is because there is a tab at the beginning of each line of your triple-quoted string, due to it being nested inside of with tab1:. Two solutions:

  1. Don’t indent the code inside the triple-quote:
with tab1:
    st.code('''
import streamlit as st

st.write("Hello, Streamlit!")
st.write("Hello, Streamlit!")
    ''', 
    'python')

Option 2: from textwrap import dedent

with tab1:
    st.code(
        dedent('''
        import streamlit as st
    
        st.write("Hello, Streamlit!")
        st.write("Hello, Streamlit!")
        '''),
        "python",
    )
1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.