-2

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

  • Does this answer your question? [How to repeat individual characters in strings in Python](https://stackoverflow.com/questions/38273353/how-to-repeat-individual-characters-in-strings-in-python) – sushanth Aug 02 '20 at 08:00
  • 1
    Welcome to StackOverflow. To avoid your question getting downvoted, you should show what attempts you have made so far, and why those attempts don't work. – Andy J Aug 02 '20 at 08:11

2 Answers2

0

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

MichaelJanz
  • 1,775
  • 2
  • 8
  • 23
0

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)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33