i have a txt file with several words on it, does anybody know how to duplicate each word two times as the next example
hello bye
hello
hello
hello
bye
bye
bye
regards
i have a txt file with several words on it, does anybody know how to duplicate each word two times as the next example
hello bye
hello
hello
hello
bye
bye
bye
regards
You could do something like this, but for sure there are better solutions:
text ="hello bye"
text_out = []
times_to_duplicate = 3
for word in text.split(" "):
for i in range(times_to_duplicate + 1):
text_out.append(word)
" ".join(text_out)
Or as list comprehention, as @Sushanth states:
"".join(f"{x} " * 3 for x in "hello bye".split())
I would recommend you, before asking a question to check the grammar and punctuation to improve the quality of your question
In python, you can replicate a string by multiplying the string n number of times.
example: this will repeat hello 3 times
>>> 'hello' * 3
'hellohellohello'
If you want a space between that, then you can do it as follows:
>>> 'hello ' * 3
'hello hello hello '
Using this as your base, you can write the code as follows to get the desired result.
txt = 'hello bye'
#now split the word and iterate thru each word by creating a new list
txt1 = [(t+' ')*3 for t in txt.split(' ')]
#you now have a new list txt1 with repeated words
#if you want it as a single string, you need to concatenate that using join
txt2 = ' '.join(txt1)
print (txt2)