Skip to content

【练习】字符串综合实战

项目简介

字符串综合实战

知识模块

  • Python 编程语言

知识点

  • 字符串操作

受众

  • 初级测试开发工程师
  • 初级Python开发工程师

作业要求

编写一个Python程序,对一个简单的故事进行如下操作:

  • 统计故事中的单词数量。
  • 查找主人公的名字在故事中的位置。
  • 将主人公的名字替换为你的名字。
  • 将故事改写为大写和小写形式。

解题思路

  • 使用字符串的方法来处理数据。

完整代码

story = "Once upon a time, in a land far away, lived a brave knight named Arthur."

# 统计故事中的单词数量
word_count = len(story.split())
print("单词数量:", word_count)

# 查找主人公的名字在故事中的位置
hero_name = "Arthur"
hero_position = story.find(hero_name)
print("主人公姓名在故事中的位置:", hero_position)

# 将主人公的名字替换为你的名字
your_name = "Alice"
new_story = story.replace(hero_name, your_name)
print("替换名字后:", new_story)

# 将故事改写为大写和小写形式
uppercase_story = story.upper()
lowercase_story = story.lower()
print("大写:", uppercase_story)
print("小写:", lowercase_story)

代码讲解

  1. len(story.split()):使用 split() 方法将字符串分割成单词列表,并通过 len() 函数获取单词数量。

  2. story.find(hero_name):使用 find() 方法查找主人公名字在故事中的位置

  3. story.replace(hero_name, your_name):使用 replace() 方法将主人公名字替换为你的名字

  4. story.upper():使用 upper() 方法将故事文本转换为大写形式

  5. story.lower():使用 lower() 方法将故事文本转换为小写形式