Home > OS >  Python: How to convert variables and their respective strings into a dataframe?
Python: How to convert variables and their respective strings into a dataframe?

Time:10-01

I have the following 4 strings

line1 = 'be nice'
line2 = '"best!"'
line3 = 'better?'
line4 = 'oh no\nbear spotted'

Is there a way for me to convert them into a table using pandas without hard coding? For example:

Line String
line1 be nice
line2 "best!"
line3 better?
line4 oh no\nbear spotted

Thank you!

CodePudding user response:

import pandas as pd

df = pd.DataFrame([
    {"Line": line, "String": eval(line)} for line in dir() 
    if line.startswith("line")
])
  • Related