I have a list of lists like this:
text_lst = [['this is a string.','this is a string2'],['this is not a string'],['this is a string with numbers!','that is all!']]
I need to add a .
for every string that does not end with a .
. Below is my code:
new_lst = []
for x in text_lst:
for x1 in x:
if x1[-1] != '.':
new_lst.append(x1 '.')
else:
new_lst.append(x1)
However, it returns a weird combination of strings and list:
[['this is a string.', 'this is a string2'],
'this is a string2.',
'this is not a string.',
'this is a string with numbers!.',
'that is all!.']
I'm expecting this type of result:
[['this is a string.', 'this is a string2.'],
['this is not a string.'],
['this is a string with numbers!', 'that is all!']]
Can you kindly let me know what did I do wrong?
Edit:
I used the wrong variable, instead of appending x1
, I append x
. Here's the result:
['this is a string.',
'this is a string2.',
'this is not a string.',
'this is a string with numbers!.',
'that is all!.']
However, any suggestion on how to preserve the list of lists format like the original one?
CodePudding user response:
Let's first learn how to add a dot to a text:
def add_dot(text):
if text.endswith(("!", ".")):
return text
return text "."
Once we have this function, we can combine it with list comprehension:
[
[add_dot(text) for text in inner_list]
for inner_list in text_lst
]
Given your sample input, the output will be:
[['this is a string.', 'this is a string2.'],
['this is not a string.'],
['this is a string with numbers!', 'that is all!']]