2

I am trying to print each line into a list element.

Currently I have:

Variable = apple
           ball
           chart
           desk

I want it into ['apple', 'ball', 'chart', 'desk']. I tried append and I get the error str object has no attribute append...

I think it is the inverse of How can I format a list to print each element on a separate line in python?

THis is the code I have so far:

for entry in variable.strip().split(","):

    variable_final = entry.lstrip()
    print variable_final 

The above code prints out:

apple
ball
chart
desk

but when I do print [variable_final] it prints out each line as a list.

Note: I still cant figure out a way to do this. Eventually all I need to do is print these lines vertically. I had asked this question earlier but it was made duplicate... I cannot find a way to print multiple lines vertically or print multiple lists vertically...

a b c d
p a h e
p l a s
l l r k
e   t 
2
  • 1
    YOu have clearly tried some code - can you post that. BTW - you don't "print" to a list - so you need to be clearer what you are trying to do. Commented Jul 20, 2014 at 20:29
  • Oh btw, I use the strip and lstrip to remove the white spaces and new line characters in "entry". Commented Jul 20, 2014 at 20:59

2 Answers 2

1

If Variable is an actual variable name that contains a multi-line string, similar to this:

Variable = "\ta\n\tb\n\tc\n\td"

then you could do:

str(Variable.replace("\n", "").split("\t")[1:])

and you can adjust this as necessary for the specific locations of the newline, tab, or other special characters in your variable string.

If the Variable = portion is actually part of the printed string itself, and the variable is called something else, say foo, then you could first do:

foo1 = foo[10:] # or however you want to skip past the 'Variable = ' part

and then just take care re: whether there is a leading whitespace or tabs when you use split.

Sign up to request clarification or add additional context in comments.

Comments

1

This might be an answer :

if you have this :

variable =
"""This is a
multiline string
and I want each line
as a separate entry"""

this this code will translate that into a list, with one list entry for each line :

lst = variable.split("\n")

1 Comment

Hi I tried this one and it gives me as seperate lists.. i.e., each line as a list and I need each line as an element of a single list...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.