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
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
.
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.