Python初学者项目练习41--反转头尾并拼接字符串

Python初学者项目练习41--反转头尾并拼接字符串 一、练习题目#定义一个函数该函数接收一个字符串和一个整数作为参数。完成一下操作#1.从字符串头部截取指定数量的字符并翻转。#2.从字符串尾部截取相同数量的字符并翻转#3.分别打印出头部和尾部翻转后与剩余部分拼接后的新字符二、代码1.初始版本代码如下defreverse(string,n)::param string:指定字符串:param n:翻转的字符数量:return:打印出头部和尾部翻转后与剩余部分拼接后的新字符 head_flippedstring[:n][::-1]head_remainingstring[n:]head_resulthead_flippedhead_remaining tail_flippedstring[-n:][::-1]tail_remainingstring[:-n]tail_resulttail_flippedtail_remainingreturnhead_result,tail_result stringNice to meet younint(input(Enter a number: ))head,tailreverse(string,n)print(f头部为{head}尾部为{tail})Enter a number: 3头部为ciNe to meet you尾部为uoyNice to meet总结string[:n] 表示从头截取到第 n 个字符[::-1] 是 Python 的技能表示将字符串倒序翻转string[-n:] 表示从倒数第 n 个字符一直截取到末尾Python 字符串切片常用操作大汇总以string HelloWorld为例