我怎么能分开一个单词不知道有多少个



当我不知道单词的长度时,我该如何将单词分开?

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
ss =4
separator: ,

我想获得:

的结果
eat,sgr,lei,app

我已经做了这么远,我很难将单词分为特定的子细分市场。

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)

您可以计算单词的长度。
您知道"句子"的长度或启动字符串:len(string)len(sentence)
(我避免使用stringString作为VAR名称,因为它们以多种语言保留为数据类型)。

您知道您需要的单词数,例如ss(我将称此wordLength)。

每个单词的长度将为 len(sentence) // wordLength-如果保证可以均匀排除。否则,使用:

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

现在为完整代码:

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"

显然,还有更多简洁的方法可以完成此任务。

您可以通过简单地导入textwrap

来做到这一点
import textwrap
String ="appleisgreat"
ss=4
print (textwrap.wrap(String, ss-1))

输出:

['app', 'lei', 'sgr', 'eat']

普通python:

>>> s = 'appleisgreat'
>>> ss = 4
>>> L = len(s)/ss
>>> separator = ","
>>> separator.join([s[i:i+L] for i in range(0,len(s),L)][::-1])
'eat,sgr,lei,app'

更好,使其成为一个函数:

def make_parts(s, ss, separator):
    # Find out what should be the length of each part
    L = len(s)/ss
    # range(0, len(s), L) is providing desired indices, e.g: 0, 4, 8, etc
    # s[i:i+L] is providing the parts
    # [::-1] is reversing the array
    # str join() method is combining the parts with given separator
    return separator.join([s[i:i+L] for i in range(0,len(s),L)][::-1])

并像

一样呼叫
>>> make_parts('appleisgreat', 4, ',')
'eat,sgr,lei,app'

最新更新