I have a python tuple whose elements are actually sentences. I want to compare the first letters of each element and if they are lowercase, I join it to the previous element. And if they aren't I just join the first element. For instance if I have:
tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.')
My result should be:
tuple1 = ('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')
This is my working code:
i=0
while i<(len(tuple1)-1):
if tuple1[i+1][0].islower():
tuple1[i] + " " + tuple[i+1]
i+=1
How can I achieve this? Thanks
You can use itertools.groupby
:
import itertools
tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.')
new_data = tuple(' '.join(i[-1] for i in b) for _, b in itertools.groupby(enumerate(tuple1), key=lambda x:x[-1][0].islower() or tuple1[x[0]+1][0].islower() if x[0]+1 < len(tuple1) else True))
Output:
('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')
Hope this does what you are looking for. I did it without using any external modules.
b = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.')
i=0
a=[]
num=0
for element in b:
print(element)
if element[i][0].islower():
a[-1]=a[-1]+element
else:
a.append(element)
num=num+1
print(a)
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