Python将字符串切割为索引处的两个字符串,并使用一个字符重叠,并将两个字符串作为列表中的两个元素返回

时间:2015-07-07 04:48:35

标签: python string

所以我想用给我写的函数将字符串切割成给定索引处的2个字符串:

#FirstProj

def run(string, index):
    print(string)
    print(index)
    print(string)
    print(string[:index])
    print(string[index:])
    return()

它与此代码结合使用:

import FirstProj

str = 'The lazy brown fox'
index = 6
myList = FirstProj.run(str,index)
print(str)
for item in myList:
    print(item)

输出假设为:

The lazy brown fox
6
The lazy brown fox
The la
azy brown fox

但我得到了这个:

The lazy brown fox
6
The lazy brown fox
The la
zy brown fox
The lazy brown fox

关于我做错的任何想法?任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

在切片字符串或列表时,当list[<start>:<end>] - start包含时,end是独占的。这意味着start索引处的值包含在切片结果中,但它仅切换到end-1,因此当您执行string[:index]string[index:]时,它们没有任何重叠索引

要获得结果,您应该这样做 -

def run(string, index):
    print(string)
    print(index)
    print(string)
    print(string[:index])
    print(string[index-1:])
    return()

此外,如果您不想在最后打印完整的字符串,只需对其进行评论(或将其删除)。代码 -

import FirstProj

str = 'The lazy brown fox'
index = 6
FirstProj.run(str,index)
#print(str)      <--------------- This is the line printing the string at the end, comment it.
#for item in myList:  <------------- Remove these lines as well, they do not do anything.
#    print(item)       <------------- Remove these lines as well, they do not do anything.

答案 1 :(得分:0)

你在执行函数后打印了字符串。评论并尝试:

#FirstProj
def run(string, index):
    print(string)
    print(index)
    print(string)
    print(string[:index])
    print(string[index:])
    return()

功能:

import FirstProj
str = 'The lazy brown fox'
index = 6
myList = FirstProj.run(str,index)
#print(str)
for item in myList:
    print(item)

<强>输出:

The lazy brown fox
6
The lazy brown fox
The la
zy brown fox

您已从函数返回任何内容,只返回空白

<强>修饰:

#FirstProj
def run(string, index):
    return(string,index,string,string[:index],string[index:])

功能:

import FirstProj
str = 'The lazy brown fox'
index = 6
myList = FirstProj.run(str,index)
#print(str)
for item in myList:
    print(item)