Home > other >  How do I make my return statement not return with parenthesis and commas?
How do I make my return statement not return with parenthesis and commas?

Time:03-12

So right now I'm trying to return a statement and print it but it returns with parenthesis:

def greeting(x):
    sp=x.split()
    return "Hello! I am ",sp[0],"and I am ",sp[1],". My favorite hobby is", sp[1]


x=input("What is your name,age, and hobby(spaced, no commas) \n")
print(greeting(x))

And it runs:

What is your name,age, and hobby(spaced, no commas) 
Jed 25 swimming

('Hello! I am ', 'Jed', 'and I am ', '25', '. My favorite hobby is', '25')

How do print it without the parenthesis and commas?

CodePudding user response:

return "Hello! I am ",sp[0],"and I am ",sp[1],". My favorite hobby is", sp[1]

The value is returned with commas because that's what you told it to do. (You can join values with commas inside a print() call and the result will be a single string message, but that's a special case.)

If you want to return a single string, then use instead of ,:

return "Hello! I am "   sp[0]   "and I am "   sp[1]   ". My favorite hobby is"   sp[1]

Or use f-string as Johnny Mopp suggested.

CodePudding user response:

From my end, I can suggest one of two ways to do this.

First is using f strings as Johnny Mopp has mentioned:

return f"Hello! I am {sp[0]} and I am {sp[1]}. My favorite hobby is {sp[2]}"

Second, I can't remember what these are called exaclty(if you do, please let me know), but this is a pretty cool and simple way to concatenate in python:

return "Hello!, I am {}, and I am {}. My favorite hobby is {}".format(sp[0], sp[1], sp[2])

In the second method, you basically put a {} everywhere you need a variable to be and after the string, you add .format() at the end and inside the parameters you specify each of the variables in the order that you had the {}'s in the string and voila, you have your string there.

  • Related