当我不知道单词的长度时,如何将单词分开?
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)
答案 0 :(得分:1)
您可以计算单词的长度
您知道"句子"的长度,或者起始字符串:len(string)
或len(sentence)
。
(我避免使用string
或String
作为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"
显然,有更简洁的方法可以完成这项任务。
答案 1 :(得分:0)
您只需导入textwrap
即可完成此操作。
import textwrap
String ="appleisgreat"
ss=4
print (textwrap.wrap(String, ss-1))
输出:
['app', 'lei', 'sgr', 'eat']
答案 2 :(得分:0)
普通蟒蛇:
>>> 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'