Hee Ra Choi Hee Ra Choi - 8 months ago 69
Python Question

How can I separate a words not know how many are there

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.


For example, If the input is:

String = appleisgreat
ss =4
separator: ,


I want to get the result of:

eat,sgr,lei,app


I have done this far, and I am having trouble dividing the words into specific sub segments.

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]
print(separate)

Answer Source

You can calculate the length of the word.
You know the length of the "sentence", or starting string: len(string) or len(sentence).
(I avoid using string or 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 wordLength).

The length of each word will be len(sentence) // wordLength - if they are guaranteed to be evenly divisible. Otherwise, use:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download