Reputation: 3
I need to repeat a word letter by letter using Python, comparing it to the size of another text.
For example:
ex_text = 'I am an example test text' # 25 characters
ex_word = 'coding'
rep_word = ''
for i in ex_word:
while len(rep_word) < len(ex_text):
rep_word += i
print(rep_word)
I'm trying to print something like:
codingcodingcodingcodingc
PS: Actually, it would be better if the output also consider the white spaces, like: c od in gcoding codi ngco
.
Upvotes: 0
Views: 72
Reputation: 5372
Here is an alternative using itertools.cycle
:
from itertools import cycle
ex_text = 'I am an example test text'
ex_word = cycle('coding')
rep_word = ''
while len(rep_word) < len(ex_text):
rep_word += next(ex_word)
print(rep_word)
The code above will result in the following output:
codingcodingcodingcodingc
You can also combine it with comprehensions and make your code more Pythonic:
from itertools import cycle
phrase = 'I am an example test text'
word = cycle('coding')
rep_word = ''.join(next(word) for _ in phrase)
print(rep_word)
Which will also result in:
codingcodingcodingcodingc
Upvotes: 0
Reputation: 1115
ex_text = "I am an example test text"
ex_word = "coding"
rep_word = ""
def find_spaces(str):
for i, ltr in enumerate(str):
if ltr == " ":
yield i
full_word, part_word = divmod(len(ex_text), len(ex_word))
rep_word = ex_word * full_word + ex_word[:part_word]
spaces = find_spaces(ex_text)
for space_index in spaces:
rep_word = rep_word[:space_index] + " " + rep_word[space_index:-1]
print(rep_word)
Upvotes: 0
Reputation: 664
ex_text = "I am an example test text"
ex_word = 'coding'
rep_word = ""
while len(ex_text)>len(rep_word):
rep_word+=ex_word
while len(ex_text)!=len(rep_word):
rep_word = rep_word[:-1]
print(rep_word)
Upvotes: 0
Reputation: 352
Here is the solution:
ex_text = "I am an example test text" #25 characters
ex_word = "coding"
rep_word = ""
while len(rep_word) < len(ex_text):
for i in ex_word:
rep_word += i
if len(rep_word) >= len(ex_text):
break
print(rep_word)
Upvotes: 2
Reputation: 142651
You can iterate range(len(ex_text))
and use modulo len(ex_word)
to get index of char in ex_word
ex_text = "I am an example test text" #25 characters''
ex_word = "coding"
rep_word = ""
for i in range(len(ex_text)):
index = i % len(ex_word) # modulo
rep_word += ex_word[index]
print(rep_word)
Result
codingcodingcodingcodingc
Upvotes: 1
Reputation: 744
Create a generator that produces the letters you want to repeat:
def coding():
while True:
for l in "coding":
yield(l)
print("".join(list(c for (_, c) in zip("I am an example test text", coding()))))
displays: 'codingcodingcodingcodingc'
Upvotes: 1
Reputation: 781004
Divide the length of ex_text
by the length of ex_word
to get the number of repetitions. If they don't divide evenly, use a slice to get the extra characters from the next repetition.
multiples, remainder = divmod(len(ex_test), len(ex_word))
rep_word = ex_word * multiples + ex_word[:remainder]
Upvotes: 5