如何在不使用split函数的情况下拆分python中的字符串

时间:2016-04-09 19:01:57

标签: python

我试图将一个句子分成单词,然后在另一行上打印每个单词。但我不允许使用拆分功能。应该使用列表等来完成。到目前为止,我有:

text=input("Enter text:")+''
L=len(text)
i=0
while i!=L:
    bi=i
    while text[i]!='':
        i=i+1
        print(text[bi:i])
        i=i+1

但这导致判决逐字逐句:

“你好”。

变为:

H
He
Hel
Hell
Hello

此外,我现在所剩下的是最后一个角色。我收到错误消息:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    while text[i]!='':
IndexError: string index out of range

这条消息是什么意思?

3 个答案:

答案 0 :(得分:2)

正如我评论你的索引不正确,两个循环都需要达到文本-1 while i < L的长度,同时添加一个空字符串不符合你的想法,text[i]永远不会等于''

In [1]: text = input("Enter text:") + ''  
Enter text:foo

In [2]: len(text) # still length 3
Out[2]: 3

In [4]: len("")
Out[4]: 0

但是如果你的单词是由空格分隔的,那么一个更简单的方法是使用for循环,当你遇到空格时打印你需要的字符并重置一个 tmp 变量:

text=input("Enter text:")
tmp = ""
for ch in text:
    # if ch is whitespace and we have some chars
    if ch.isspace() and tmp:
        print(tmp)
        tmp = ""
    else:
        tmp += ch
# catch last word
if tmp:
     print(tmp)

答案 1 :(得分:1)

您收到错误是因为Python被编入零索引:

s = "this is a string that I want to split"

words = [] # create an empty list of your words
chars = [] # create an empty list of characters

for char in s:

    if char == " " and chars: # if the character is a space and we've stored some chars
        words.append("".join(chars)) # combine the stored chars into a word and add it to 
                                     # the word lise
        chars = [] # clear out the stored chars

    elif char != " ":
        chars.append(char) # otherwise, store the char if it's not a space

if chars:
    words.append("".join(chars)) # add the last word found to the word list

您甚至可以通过不使用它们来解决不匹配的索引问题。只要有可能,让Python使用for循环来迭代列表或字符串来管理索引:

for (Set<Integer> s : SetUtils.powerSet(mySet))

请注意,通过使用 Private Sub GenerateInvoiceButton_Click() Dim AccountNumberRange As Range Dim AccountColumn As Range Dim LastAccountColumn As Long Dim AccountDataRange As Range Dim DataWS As Worksheet Dim DashBoardWS As Worksheet Dim AccountNumber As String Dim SelectedAccountLastRow As Long Dim SpecificAccountDataSet As Range Dim DashBoardDataStartPosition As Range 'Change DataSheet to the sheet name of your sheet with the account data Set DataWS = ThisWorkbook.Sheets("DataSheet") 'Change DashBoardSheet to the sheet name of your sheet with the DashBoard Set DashBoardWS = ThisWorkbook.Sheets("DashBoardSheet") 'This should be set to the cell under the "UnitCost" in the INITIAL TAKE-ON COST section on your DashBoardSheet Set DashBoardDataStartPosition = DashBoardWS.Cells(16, "F") 'This should be the cell in which you insert the account number AccountNumber = DashBoardWS.Range("G3").Value 'Quititng the Code if there is no Account Number If AccountNumber = Empty Then MsgBox "Please Insert an Account Number" End End If With DataWS LastAccountColumn = .Columns(.Columns.Count).End(xlToLeft).Column End With 'Starting from 4 because your account number start at Column D Set AccountNumberRange = DataWS.Range(DataWS.Cells(1, 4), DataWS.Cells(1, LastAccountColumn)) Set AccountColumn = AccountNumberRange.Find(What:=AccountNumber) If AccountColumn Is Nothing Then MsgBox "Account Number: " & AccountNumber & _ vbCr & vbCr & "Not Found!" & vbCr & _ vbCr & _ "Please enter a valid Account Number." Else With DataWS SelectedAccountLastRow = .Rows(.Rows.Count).End(xlUp).Row 'Starting at Row 2 because of your header row Set SpecificAccountDataSet = .Range(.Cells(2, AccountColumn.Column), .Cells(SelectedAccountLastRow, AccountColumn.Column)) SpecificAccountDataSet.Copy End With DashBoardDataStartPosition.PasteSpecial Paste:=xlPasteValues End If End Sub 循环,您不必手动管理任何索引。

答案 2 :(得分:-1)

如果使用列表不是一项硬性要求,您可以尝试使用正则表达式。此正则表达式将字符串分解为单词并返回包含单词的列表。

(\S+)\s*

Regex101