How can I make the words separate when I do not know the length of the word?
Split the string into the specified number of sub segments where each sub
segment consists of a contiguous block of characters. Finally, reverse all the sub segments divided by
separator characters to build a new String and display it.
String = appleisgreat
string = input("Enter a stirng:")
ss = eval(input("Enter the number of sub segments:"))
separator = eval(input("Enter the separator:"))
worldlist = list(string)
separate = worldlist/[ss]
You can calculate the length of the word.
You know the length of the "sentence", or starting string:
(I avoid using
String as var names, as they are reserved in many languages as data types).
You know the number of words you need, as
ss (I'll be calling this
The length of each word will be
len(sentence) // wordLength - if they are guaranteed to be evenly divisible.
wordLength = len(sentence) // wordLength # // TRUNCATES, so if if its not evenly divisible, # the "fractional" number of letters would get left out. # instead, let's increase all the other the word lengths by one, and now # the last word will have the remaining letters. if len(sentence) % wordLength == 0: wordLength += 1
Now for the full code:
sentence = "appleisgreat" ss = 4 seperator = "," numWords = ss # rename this variable to be descriptively consistent with my other vars wordLength = len(sentence) // numWords # use // to truncate to an integer print(wordLength) ## 3 # create a list of ss strings, each of length segmentSize wordlist =  for wordNum in range(numWords): startIndex = wordNum * wordLength # print (startIndex, startIndex + wordLength) ## 0 3, 3 6, 6 9, 9 12 word = sentence[startIndex : startIndex + wordLength] # since you want the list in reverse order, add new word to beginning of list. # If reverse order is not required, `append` could be used instead, as wordlist.append(word) wordlist.insert(0, word) print(wordlist) ## ["eat", "sgr", "lei", "app"] # lists are iterables, so `join` can be used here to "join" the strings together, seperated by "seperator" result = seperator.join(wordlist) print(result) ## "eat,sgr,lei,app"
Obviously, there are much more concise ways to accomplish this task.