I created a function in python to count the length of words while ignoring punctuation symbols. For example if I have the sentence : "Haven't there been 3 blackouts today?
The result should be the following: [6,5,4,1,9,5]
I am able to get these results with the following function I created:
import string
def word_length_list(given_string):
clean_string = given_string.translate(str.maketrans('','',string.punctuation))
word_lenght_list = list(map(len, clean_string.split()))
return word_lenght_list
given_string = "Haven't there been 3 blackouts today?"
word_length_list(given_string)
This function gives me the expected result which is: [6, 5, 4, 1, 9, 5]
However if I give it a really long string such as:
given_string = "Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function."
It gives me the result in the following way:
[7,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
15,
3,
6,
2,
3,
8]
Does anyone have any ideas of how I could make my list return the result horizontally for both short string and long string? Any suggestions would be greatly appreciated.
I am using jupyter notebook to run the code as a .ipynb
You can use the zip() function to join lists together. The zip() function will iterate tuples with the corresponding elements from each of the lists, which you can then format as Michael Butscher suggested in the comments. Finally, just join() them together with newlines and you have the string you want.
The naive method can be used to print the list vertically vis. using the loops and printing each index element of each list successively will help us achieve this task. Using zip function, we map the elements at respective index to one other and after that print each of them.
In a separate cell run the command %pprint
This turns pretty printing off. The list will now display horizontally.
Join the representation of the list's items with ', '
,
l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))
Output:
3.14, 'string', ('tuple', 'of', 'items')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With