简体   繁体   中英

Add string or symbol before and after the list in python

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])     

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM