Search code examples
pythonescapingstring-concatenationstring-literals

Pyschool Quiz--String Concatenation


Here's the quiz question:

Adding two strings or making multiple copies of the same string.

Examples:

greetings = "Hello World"

len(greetings) # get the length of string

 11

greetings[0] # get the 1st character

 'H'

print underline("Good Day")

 Good Day
 ________

# Write a function, given a string of characters, return the string together with '_'s of the same length.

My first attempt was:

def underline(title): 
  print title
  print len(title) * '_'

...which somewhat passes visually but returns a 'None' value also. (any idea why that is?) So instead I tried:

def underline(title): 
  print title, \nlen(title) * '_'

...and get an "unexpected character after line continuation character" error. Turning here after Google was less than helpful with this error.


Solution

  • Well you don't want to print those strings, you want to return them.

    So create a string that combines them together (separated by a newline character) and return that.

    def underline(title):
        return title + '\n' + len(title) * '_'