What is the best way to create a string array in python?

I'm relatively new to Python and it's libraries and I was wondering how I might create a string array with a preset size. It's easy in java but I was wondering how I might do this in python.

So far all I can think of is

strs = ['']*size

And some how when I try to call string methods on it, the debugger gives me an error X operation does not exist in object tuple.

And if it was in java this is what I would want to do.

String[] ar = new String[size];
Arrays.fill(ar,"");

Please help.

Error code

    strs[sum-1] = strs[sum-1].strip('\(\)')
AttributeError: 'tuple' object has no attribute 'strip'

Question: How might I do what I can normally do in Java in Python while still keeping the code clean.


Solution 1:

In python, you wouldn't normally do what you are trying to do. But, the below code will do it:

strs = ["" for x in range(size)]

Solution 2:

In Python, the tendency is usually that one would use a non-fixed size list (that is to say items can be appended/removed to it dynamically). If you followed this, there would be no need to allocate a fixed-size collection ahead of time and fill it in with empty values. Rather, as you get or create strings, you simply add them to the list. When it comes time to remove values, you simply remove the appropriate value from the string. I would imagine you can probably use this technique for this. For example (in Python 2.x syntax):

>>> temp_list = []
>>> print temp_list
[]
>>> 
>>> temp_list.append("one")
>>> temp_list.append("two")
>>> print temp_list
['one', 'two']
>>> 
>>> temp_list.append("three")
>>> print temp_list
['one', 'two', 'three']
>>> 

Of course, some situations might call for something more specific. In your case, a good idea may be to use a deque. Check out the post here: Python, forcing a list to a fixed size. With this, you can create a deque which has a fixed size. If a new value is appended to the end, the first element (head of the deque) is removed and the new item is appended onto the deque. This may work for what you need, but I don't believe this is considered the "norm" for Python.

Solution 3:

The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.