Reputation: 960
I have a list of numbers and want to add character or symbol before and after the list.
I just want to add array( in the beginning and ) in the end of list_1. I tried the following:
list_1 = [1, 2, 3, 4]
x = 'array('
y = ')'
a = str(x) + list_1 + str(y)
but it give me error :cannot concatenate str and list
My expected output is
array([1, 2, 3, 4])
Upvotes: 1
Views: 339
Reputation: 13929
Try either a = x + str(list_1) + y
or f"array({list_1})"
. The latter is a debugged version of the suggestion by @sahasrara62.
The reason you got the error is, well, you can't concatenate str and list as the error message says. In your code, you are asking python to add a string x
and a list list_1
, which python cannot do. (By the way x
and y
are already strings, so str(x)
and str(y)
do nothing. They are just x
and y
respectively.) You need to explicitly convert the list into string by using str(list_1)
. After that you can now concatenate it with other strings such as x
and y
.
Upvotes: 1