+3 votes
in Programming Languages by (73.8k points)
I have a list of strings and want to calculate the length of each string in the list. What function should I use for this?

E.g.

x= ['hello', 'brothers', 'Bharat', 'Delhi']

I want [5, 8, 6, 5] as the answer.

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use Numpy's char module. It has a function str_len() that returns length element-wise.

E.g.

>>> from numpy import char
>>> aa=['hello', 'brothers', 'Bharat', 'Delhi']
>>> char.str_len(aa)
array([5, 8, 6, 5])

You can also try the following approach to get the length of each string in a list.

>>> aa=['hello', 'brothers', 'Bharat', 'Delhi']
>>> [len(a) for a in aa]
[5, 8, 6, 5]


...