简单计算器,单层循环输出乘法表,字符串方法的使用,格式化输出

本文展示了如何使用Python编写一个简单的四则运算计算器,确保输入为数字,并实现99乘法表的打印。同时,介绍了字符串处理方法如strip, replace, split等,以及格式化输出和对齐方式。示例代码详细,适合初学者学习。
  • 写一个简单(±*/)的计算器, 确保输入的都是数字(如果不是数字,让它重新输入)

    输入格式必须是: 7+8 => 输出格式是 7 + 8 = 15

    data = input("请输入要进行运算的式子:")
    x = int(data[0])
    y = data[1]
    z = int(data[2])
    if y == "+":
        print("{}+{}={}".format(x, z, x+z))
    elif y == "-":
        print("{}-{}={}".format(x, z, x-z))
    elif y == "*":
        print("{}x{}={}".format(x, z, x * z))
    elif y == "/":
        print("{}/{}={}".format(x, z, x / z))
    
  • while单层循环完成9 * 9乘法表

    i = 1
    j = 1
    while i < 10:
        print(i, "x", j, "=", i * j, end="\t")
        if i == j:
            j = 0
            i += 1
            print()
        j += 1
    
  • str字符串中的strip, replace, split, partition, expandtabs, join
    center, ljust, rjust方法

strip 返回字符串的剪裁版本。
txt = "     banana     "

x = txt.strip()

print("of all fruits", x, "is my favorite")
replace 	返回字符串,其中指定的值被替换为指定的值。
txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)
split 	在指定的分隔符处拆分字符串,并返回列表
txt = "welcome to China"

x = txt.split()

print(x)
partition 返回元组,其中的字符串被分为三部分。
txt = "I could eat bananas all day"

x = txt.partition("bananas")

print(x)
expandtabs 	设置字符串的 tab 尺寸。
txt = "H\te\tl\tl\to"

x =  txt.expandtabs(2)

print(x)
join 把可迭代对象的元素连接到字符串的末尾。
myTuple = ("Bill", "Steve", "Elon")

x = "#".join(myTuple)

print(x)
center 返回居中的字符串。
txt = "banana"

x = txt.center(20)

print(x)
ljust 	返回字符串的左对齐版本。
txt = "banana"

x = txt.ljust(20)

print(x, "is my favorite fruit.")
rjust 返回字符串的右对齐版本。
txt = "banana"

x = txt.rjust(20)

print(x, "is my favorite fruit.")
  • 格式化输出:
    姓名 年龄 性别 家庭住址
    xxx xxxx

    list_data = [{name: xxx, age: xxx, gender: xxx, address}, .....]
    包含居中对齐,向左对齐, 向右对齐
    
list_data = [{"name": "张三", "age": "20", "gender": "男", "address": "西安市长安区"}]
print(list_data[0].keys())
for i in list_data[0].keys():
    print(i.center(20), end=" ")
print()
for i in list_data[0].values():
    print(i.center(19), end=" ")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_59138290

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值