How to Insert a Word into a List in Python

Insert word into specific position in a list

The method used here is to iterate through the original list, splitting each item into two halves and building the final item string using .format before appending it into a new list.

orig_list = ["The house is red.", "Yes it is red.", "Very very red."]
new_list = []
word = 'super'

for item in orig_list:
first_half = item[:len(item) // 2]
second_half = item[len(item) // 2:]
item = '{}{}{}{}{}'.format(word, first_half, word, second_half, word)
new_list.append(item)

Python - Insert data into a word document using a list

I think this should give you the result you are looking for:

from docx import Document

document = Document('mydocx.docx')
my_list = ['Some key points here', 'We expected values to be higher. That is fine', 'final attributes', 'local dataset']
my_second_list = ['My random data', 'Flowers. That is fine', 'happy birthday', 'puppies']

i = 0
j = 0
for para in document.paragraphs:
if 'Keyword_one' in para.text and i < len(my_list):
para.add_break()
para.add_run(my_list[i])
i += 1
elif 'Keyword_two' in para.text and j < len(my_second_list):
para.add_break()
para.add_run(my_second_list[j])
j += 1

document.save("mydocx.docx")

In the case where a paragraph contains both keywords and you want it to add from both lists, change the elif to if.

Adding words to list

You need to test for an empty line and skip the append in that case.

def words(filename):
word = []
file = open(filename)
for line in file:
line=line.strip()
if len(line):
word.append(line)
return word

How to add a word before the last word in list?

Here is one way, but I have to convert the int's to strings to use join:

myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]
print(",".join(smyList), 'and', myList[-1])

gives:

1,2,3 and 4

The -1 index to the list gives the last (rightmost) element.

Python Inserting a String Into a List After Three Numbers Have Been Printed

you can use enumerate to get the index while iterating.

sentence = 'i do not know how to do this'
sentence = sentence.split()

sentence = " ".join([words[-1:] + words[:-1] + 'mu' for words in sentence])
result = []
for idx, word in enumerate(sentence.split()):
if idx > 1 and idx % 3 == 0:
result.append("emu")
result.append(word)

print(" ".join(result))

Another mistake you are doing is inserting element into an array while iterating it.

How to turn each word in a string in a list into elements in a list

The most simple way to go with the current code itself is to make use of the extend methods provided to lists:

   l = []
for word in data_txt_file:
s = word.split(" ")
l.extend(s)


Related Topics



Leave a reply



Submit