pythonpandasspintax

How to add a line break in a string inside a DataFrame?


I am trying out this text spinner but I find it troubling when I try to add a line break in the string that gets created. As you can see in the code below, I add "\n" but the output generated by the print(and also the content of the DataFrame) does not contain this break.

import spintax

df = pd.DataFrame()

for i in range(0, 50):
    data = spintax.spin("{option1|option2}" +  "\n" + " blablabla ")
    df = df.append({'A': data}, ignore_index=True)

df['A'] = df['A'].str.replace(r'\s+', " ")
print(df)

How could I make it work?

print(df) output looks like this:

                         A
0   option2 blablabla 
1   option2 blablabla 
2   option2 blablabla 
3   option2 blablabla 
4   option2 blablabla 

Solution

  • So the problem lies when you replace r\s+ which also matches line breaks and replaces them with white spaces. source.

    If you comment your line then following will retain the newline character in strings.

      import spintax
        df = pd.DataFrame()
        for i in range(0, 50):
            data = spintax.spin("{option1|option2}" +  "\n" + " blablabla ")
            df = df.append({'A': data}, ignore_index=True)
    
        # df['A'] = df['A'].str.replace(r'\s+', " ")
    
        print(df)
    

    Is that what you wanted to achieve?