[Tutor] New Line Problem

Alan Gauld alan.gauld at yahoo.co.uk
Fri Feb 2 04:26:59 EST 2018


On 02/02/18 02:44, Anna Lapre wrote:
> I am having a problem with creating a new line in a return statement for a
> function. It has a mix of a bunch of strings and variables. Everything that
> I want included will print, except for the new lines. I have tried "\n" but
> with no luck. Do you have any recommendations? Thanks.
> 
> http://py3.codeskulptor.org/#user301_SIdBE94Q8yi3qtM.py
> (it's the second function)

For a short function like this just post the code in the message, its
much easier to work with.

def singleline_diff_format(line1, line2, idx):
    length_line1 = len(line1)
    length_line2 = len(line2)
    if (idx + 1) <= length_line1 and (idx + 1) <= length_line2:
        equal = "===================================================="
        code = (line1 +
                equal[0:idx] + "^" +
                line2)
        return code
    else:
        return ""

You just need to add newline characters around the equal line.

        code = (line1 +
                '\n'+ equal[0:idx] + "^" + '\n' +
                line2)

Or using a format string:

code = "%s\n%s\n%s" % (line1,equal[:idx]+'^',line2)

You also are not implementing the part of your specification
that says return an empty string if either input contains a
newline. testing the lengths does not work:

>>> s = "fred\njones"
>>> len(s)
10

You need to test whether '\n' is in the string.

By the way, your first function is much more complicated
than it needs to be, it is very inefficient and I'm pretty
sure its wrong too. Try:

singleline_diff("part trap", "part part")

And see if you get the right answer.

But you can make it a whole lot simpler if you just
compare the characters one by one and stop messing
around with indexes.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list