3

Take care of the comma (in Python)

 3 years ago
source link: http://www.donghao.org/2021/04/29/take-care-of-the-comma-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Take care of the comma (in Python)

Think about the result of this snippet:

def concat(a, b):
    return a + "_" + b

left = "hello",
right = "world"

print(concat(left, right))
Python
xxxxxxxxxx
def concat(a, b):
    return a + "_" + b
left = "hello",
right = "world"
print(concat(left, right))

Should be “hello_world”, right?

But the actual result is an error:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print(concat(left, right))
  File "test.py", line 2, in concat
    return a + "_" + b
TypeError: can only concatenate tuple (not "str") to tuple
Python
xxxxxxxxxx
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print(concat(left, right))
  File "test.py", line 2, in concat
    return a + "_" + b
TypeError: can only concatenate tuple (not "str") to tuple

and the error seems hard to understand.

As a matter of fact, the reason for this error is we have just put a comma after “hello” so the value of variable “left” is a tuple (“hello”,) instead of a string “hello”

Even for this shortcode sample, it is hard to find the reason, not mention in the real program to find out the root. For the first time in recent 3 years, I began to miss the strong-type programming language like C…

Like this:

Loading...
4:06 am ROBIN DONG develope
python
Leave a comment

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK