Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...