-2

Let's say I have the following function:

def string_function(word):
    print(word)
    

How do I make it so that if I call a separate print function, I can concatenate the string from that function to the new print?

E.g. the following will raise a TypeError, but it's what I'm trying to do. :

print("foo") + string_function("bar")

I know that I can just change the print into a return, but I'm asking if it's possible with a print.

Adnos
  • 9
  • 1
  • 4
  • it would be better if your function returns something instead of printing – buran Jan 17 '21 at 13:20
  • 1
    Does this answer your question? [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – Stefan Falk Jan 17 '21 at 13:23

2 Answers2

0

You could use the end argument of the print function to display both messages on the same line:

print("foo", end="")
string_function("bar")
Marc Dillar
  • 471
  • 2
  • 9
0

The TypeError is because neither print() nor string_function() return anything (except the default return value None).

What you are doing here is, essentially, adding None with a None:

None + None  # This is what causes your TypeError

What you probably want is using the end argument of print() and set it to an empty string:

print("foo", end="")
print("bar")

If you want to format or concatenate strings you have several options:

a = "foo"
b = "bar"

print(f"{a} {b}")        # Use format string
print(a + " " + b)       # Concatenation using +
print(" ".join((a, b)))  # Using str.join

Just to name the most common ones.

Stefan Falk
  • 23,898
  • 50
  • 191
  • 378