0

I want to add a string, lets say "NEWYEAR", to an array with a length that is not necessarily the same as the length of "NEWYEAR" - whereas the array should be "fully" filled with the string, leaving no whitespaces behind. Roughly sketched, this is what I have in mind:

array = [0,0,0,0,0,0,0,0,0] 
some_string="NEWYEAR" 

#add some_string to array until no place is left in array. 
#some_string should repeat itself until upper condition is fulfilled. 

array = ["N","E","W","Y","E","A","R","N","E"] 

Could you tell me an intuitive way to accomplish my goal ?

1
  • You can just create a list with equal size to array and its contents are from NEWYEAR Commented Jan 1, 2021 at 17:45

5 Answers 5

1

One could do

(list(some_string)*(int(len(array)/len(some_string))+1))[:len(array)]

or

[some_string[i%len(some_string)] for i in range(len(array))]
Sign up to request clarification or add additional context in comments.

2 Comments

Would this be over-filled the original array then? PO asked for fully filled only, not clear over-filled is an option then. >>> array ['N', 'e', 'w', 'Y', 'e', 'a', 'r', 'N', 'e', 'w', 'Y', 'e', 'a', 'r'] # len is 14!
@DanielHao Yea. You are right. Don't know why. Removed first option. Thanks.
0

There are many ways to achieve this but I think that one of the simplest is to use the % operator.

size_of = 15

word = 'NEWYEAR'

array = []

size_of_word= len(word)

size_of_word = len(word)
for letter in range(size_of):
    array.append(word[letter%size_of_word])

Comments

0
str_len = len(some_string)
arr_len = len(array)
for i in range(arr_len):
   array[i] = some_string[i%str_len]

print(array)

1 Comment

Often "just code" answers aren't useful, or at best they could be a lot more useful with an explanation.
0

Code

len_ar = int(input("Enter Length : "))
arr_lst = [None]*len_ar
str_nam = input("Enter String : ")
f_str = (str_nam * (int(len_ar/len(str_nam))+1))[:len_ar]

for i in range(len_ar):
    arr_lst[i] = f_str[i]

print(arr_lst)

Comments

0

One possible way

import random

array = [0,0,0,0,0,0,0,0,0]
some_string = "NEWYEAR"

new_string = ''.join(random.choice(some_string) for i in range(len(array)))
array[:] = [char for char in new_string]

print(array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.