1

I have a yaml file where i have assigned

apple: "iamafruit iamtasty iamhealthy"

in my python file

a = apple print a

iamafruit iamtasty iamhealthy

but i want to be displayed as

iamfruit\n iamtasty\n iamhealthy

1
  • how do i assign a multiline string to a variable Commented Jul 21, 2017 at 10:21

2 Answers 2

2

Have a look at Python tutorial section on strings.

For a string literal to span multiple lines, you can end each line with a continuation character, a backslash:

a = "apple\n\
tasty\n\
healthy"

or you can use the triple-quotes:

a = """apple
tasty
healthy"""

If your string is short, and you don't care about readability, you can just include the newline characters, like this:

a = "apple\ntasty\nhealthy"

To combine several lines (strings), you can also use str.join() on the newline character:

a = '\n'.join(['apple', 'tasty', 'healthy'])

Any of these methods will produce:

>>> print(a)
apple
tasty
healthy

If you have a list of words which you wish to convert to a multiline string, use you can use str.split() in combination with str.join():

apple = "apple tasty healthy"
lines = '\n'.join(apple.split())
Sign up to request clarification or add additional context in comments.

Comments

0
apply = "iamafruit iamtasty iamhealthy"
apple = apple.replace(" ", "\n ")
print apple

now apply will be

apple = "iamafruit\n iamtasty\n iamhealthy"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.