Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

Can I store strings in python array?

from array import *
val=array('u',["thili","gfgfdg"])
print(val)

When I compiled above python code, the compiler showed an error.

enter image description here

What is the problem in my code.can not store strings in python array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, the Python interpreter is written in C language language and that array library is includes array of C language (In fact, it is not array of Python, it is array of C). A string is array of chars in C (char is a number which act like one letter). You are passing two unicode strings as argument to the array function but one of these unicode strings is already an array for C. So you cant pass two unicode string to array function. Look at that:

from array import array
my_array = array("u","thili") # no error
print(my_array) # array('u', 'thili')

other_array = array("u",["thili","gfgfdg"])
Traceback (most recent call last):
  File "<pyshell#5>", line 3, in <module>
    my_array = array("u",["thili",""])
TypeError: array item must be unicode character

As you can see array of unicode string is not much different than normal unicode string. Because it contains only one string. You should use list or tuple class instead. And the list class in Python is array of Python.

my_list = ["thili","gfgfdg"] # same as: my_list = list("thili","gfgfdg")
my_tuple = ("thili","gfgfdg") # same as: my_tuple = tuple("thili","gfgfdg")

Dont forget that tuples are unmutable but lists are mutable. If you want to change value of any index, then use list. Tuples are good when you want to optimize your memory (RAM) usage. Finally tuples are more faster than lists in terms of creation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...