Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在某些索引处反转和连接字符串?_Python_String_Python 3.x_Concatenation_Reverse - Fatal编程技术网

Python 如何在某些索引处反转和连接字符串?

Python 如何在某些索引处反转和连接字符串?,python,string,python-3.x,concatenation,reverse,Python,String,Python 3.x,Concatenation,Reverse,在我的作业中,我需要首先拿出一个函数来反转输入的字符串(我已经使用下面的代码完成了) def倒档: 如果len(s)类似于: def concatreverse(s, i): return s[:i] + reverse(s[i:]) 你可以这样做: s = 'laptop' i = 3; # split the string into two parts part1,part2 = s[0:i], s[i:] # make new string starting with rev

在我的作业中,我需要首先拿出一个函数来反转输入的字符串(我已经使用下面的代码完成了)

def倒档:
如果len(s)类似于:

def concatreverse(s, i):
    return s[:i] + reverse(s[i:])

你可以这样做:

s = 'laptop'
i = 3;

# split the string into two parts
part1,part2 = s[0:i], s[i:]

# make new string starting with reversed second part.
s2 = part2[::-1] + part1
print(s2) 
# prints: potlap

结合其他两个答案,实现反向功能:

def concatreverse(s, i):
    """This function takes in a string, s, which
    is split at an index, i, reverses the second of the split,
    and concatenates it back on to the first part"""

    #Takes your inputs and processes
    part1,part2 = s[0:i], s[i:]

    #Reverse part2 with the function you already created
    #this assumes it is accessible (in the same file, for instance)
    rev_part2 = reverse(part2)

    #concatenate the result
    result = part1 +rev_part2

    #Give it back to the caller
    return result

作为初学者,逐行进行测试或使用解释器进行测试有助于准确了解情况:)

这很有意义。但我不是必须先定义范围吗?什么范围?从你的问题中我了解到,我是按指数分割的。不过,您可以检查索引是否大于字符串的长度。这太好了。哦,好的。我想我必须将范围定义为len(s)或与之相关的东西。不需要<代码>[::-1]
这将反转字符串或任何列表。这是使用
reverse.
函数的另一种选择。我在新函数中使用了类似的东西。谢谢你的建议!与我的导师相比,解释要简单得多。python有点便宜,因为你可以走得很远,而不知道到底发生了什么,但如果你在追求计算机科学,也许值得你对他们的解释稍微动一下脑筋:)不客气,祝你好运!
def concatreverse(s, i):
    """This function takes in a string, s, which
    is split at an index, i, reverses the second of the split,
    and concatenates it back on to the first part"""

    #Takes your inputs and processes
    part1,part2 = s[0:i], s[i:]

    #Reverse part2 with the function you already created
    #this assumes it is accessible (in the same file, for instance)
    rev_part2 = reverse(part2)

    #concatenate the result
    result = part1 +rev_part2

    #Give it back to the caller
    return result