+3 votes
in Programming Languages by (17.0k 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?


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

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

1 Answer

0 votes
by (28.9k points)

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


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