python字符串练习与答案

1.定义两个变量x,y,分别赋值3,5,用eval()函数计算x的y次方的值。

x = 3

y = 5

print(eval('x**y'))

2.输入我出生年份和月份,分别赋给变量year和month,然后用format()方法输出。

格式要求:宽度20,居中对齐,-号填充

year = int(input('请输入你的出生年份:'))

month = int(input('请输入你的出生月份:'))

print('我出生于{:-^10}年{:-^10}月'.format(year,month))

3.输入浮点数3.14159,屏幕输出¥¥¥¥¥¥3.14 (格式要求:宽度10,右对齐,保留两位小数,¥号填充。

num = 3.14159

print('{:¥>10.2f}'.format(num))

4.已知一个字符串为 "hello_world_yoyo",请用split()方法得到一个["hello","world","yoyo"]

string = 'hello_world_yoyo'

print (string.split('_'))

5.有个列表 ["hello", "world", "python"],请用join()方法列表里面的字符串联起来,得到字符串 "hello_world_python"。

symbol = '_'

a = ['hello','world','python']

print(symbl.join(a))

6.把字符串 "We are happy." 中的每个空格替换成"%20",输出:"We%20are%20happy."。

str = 'we are happy'

print(str.replace(' ','%20'))

7.假设我们给fruits 赋值列表['apple', 'banana', 'orange', 'apple', 'grape', 'apple'],我们怎么统计列表中apple出现的次数(用count()函数)。

fruits = ['apple','banana','orange','apple','grape', 'apple']

a = fruits.count('apple')

print(a)

8.假设我们给text 赋值字符串"Python is a powerful programming language. Python is widely used in web development, data analysis, and artificial intelligence."我们怎么统计字符串中Python出现的次数(用count()函数)。

text = "Python is a powerful programming language. Python is widely used in web development, data analysis, and artificial intelligence."

b = text.count('Python')

print(b)

9.用input()输入你的零花钱,用变量lhq存储;输入你每天的平均消费,用变量xf存储;输入本月的天数,用户变量x存储。然后计算出你本月还剩多少余额,存为变量yu,使用format()函数输出'本月我还剩余元。

pockt_money = int(input('请输入你的零花钱:'))

consumption = int(input('请输入你的消费金额:'))

month_day = int(input('请输入当月天数:'))

remaining_sum = int(pockt_money-consumption*month_day)

print('本月我还剩余{}元'.format(remaining_sum))

习题来源于其他博主的文章,本文只是记录解题过程!

相关推荐
Yan-英杰44 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779132 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥3 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
小喵要摸鱼7 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover17 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
mengyoufengyu8 小时前
算法12-贪心算法
python·算法·贪心算法
T_Y99438 小时前
pythonrsa加密与sha256加密
python