Lynn L Crawford
Lynn L Crawford

Reputation: 41

Python instructional code to print long strings with line breaks

What's wrong with this code? Except for the print statement, it is the direct answer code from a Udacity learning python lesson. It suggests br as an html response, but to me that didn't make sense in python. The python run results print the letters <BR> between every letter of the string.

def breakify(strings):
    return "<br>".join(strings)

print(breakify("Haiku frogs in snow" "A limerick came from Nantucket" "Tetrametric drum-beats thrumming,"))

Output:

H<br>a<br>i<br>k<br>u<br> <br>f<br>r<br>o<br>g<br>s<br> <br>i<br>n<br> <br>s<br>n<br>o<br>w<br>A<br> <br>l<br>i<br>m<br>e<br>r<br>i<br>c<br>k<br> <br>c<br>a<br>m<br>e<br> <br>f<br>r<br>o<br>m<br> <br>N<br>a<br>n<br>t<br>u<br>c<br>k<br>e<br>t<br>T<br>e<br>t<br>r<br>a<br>m<br>e<br>t<br>r<br>i<br>c<br> <br>d<br>r<br>u<br>m<br>-<br>b<br>e<br>a<br>t<br>s<br> <br>t<br>h<br>r<br>u<br>m<br>m<br>i<br>n<br>g<br>,

Upvotes: 0

Views: 67

Answers (1)

wjandrea
wjandrea

Reputation: 32954

The strings are being concatenated due to string literal concatenation.

Simply put them in a list (or tuple) and separate them with commas.

Example with shorter strings for readability:

print(breakify(["Haiku", "limerick", "drum"]))

Output:

Haiku<br>limerick<br>drum

You got the output you did because str.join takes any iterable, and a string is an iterable. For example:

>>> '.'.join('hello')
'h.e.l.l.o'

Upvotes: 1

Related Questions