简体   繁体   中英

How to repeat a word letter by letter based on the length of other string?

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 .

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]

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)

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'

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
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) 
    

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
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM