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

一、练习题目

#定义一个函数,该函数接收一个字符串和一个整数作为参数。完成一下操作:

#1.从字符串头部截取指定数量的字符并翻转。

#2.从字符串尾部截取相同数量的字符并翻转

#3.分别打印出头部和尾部翻转后与剩余部分拼接后的新字符

二、代码

1.初始版本

代码如下:

c 复制代码
def reverse(string, n):
    """
    :param string: 指定字符串
    :param n: 翻转的字符数量
    :return: 打印出头部和尾部翻转后与剩余部分拼接后的新字符
    """
    head_flipped = string[:n][::-1]
    head_remaining = string[n:]
    head_result = head_flipped + head_remaining

    tail_flipped = string[-n:][::-1]
    tail_remaining = string[:-n]
    tail_result = tail_flipped + tail_remaining

    return head_result, tail_result


string = "Nice to meet you"
n = int(input("Enter a number: "))
head, tail = reverse(string, n)
print(f"头部为:{head},尾部为:{tail}")

Enter a number: 3

头部为:ciNe to meet you,尾部为:uoyNice to meet


总结

  1. string:n 表示从头截取到第 n 个字符
    ::-1 是 Python 的技能,表示将字符串倒序(翻转)
    string-n: 表示从倒数第 n 个字符一直截取到末尾
  2. Python 字符串切片常用操作大汇总
    以string = "HelloWorld"为例
相关推荐
happylifetree2 小时前
Python67:核心语法-函数进阶-参数类型(函数作为参数)
python
小羊没烦恼!2 小时前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
quantdash_cc3 小时前
从实时行情到价格观察表:用 Python 和 Pandas 构建策略输入数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
镜子AI3 小时前
镜子AI工程实践:用 Python 做 GEO 实体一致性审计,并自动生成 JSON-LD 结构化数据
人工智能·python·json
2601_962885727 小时前
如何用 Python 计算 VaR 和 CVaR(在险价值)?
开发语言·python
李航19837 小时前
DeepSeekAI建模三 - 实战建模一组柜子
人工智能·python·计算机视觉·ai·ai编程
严谨的麻辣烫8 小时前
静态代理 IP 的出口一致性如何验证?Python 请求检测与异常排查
开发语言·python·http·网络安全
我命由我123459 小时前
5-1.Python 编码进阶 - 函数进阶(参数、返回值、递归、函数作为参数传递、lambda 匿名函数)
java·服务器·数据库·后端·python·java-ee·python3.11
FITA阿泽要努力9 小时前
Fork Agent:共享上下文的艺术
开发语言·python·agent
DeeGLMath9 小时前
optimtool最新版研究梯度优化
python·optimtool·梯度优化