栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python实现一个简单(+-*/)的计算器、while单层循环完成9 * 9乘法表、str字符串中的方法的使用、格式化输出个人信息

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python实现一个简单(+-*/)的计算器、while单层循环完成9 * 9乘法表、str字符串中的方法的使用、格式化输出个人信息

目录

1. 一个简单(+-*/)的计算器

2. while单层循环完成9 * 9乘法表

3. str字符串中的方法的使用

3.1 strip(self, chars=None, /) 剥离

3.2 replace(self, old, new, count=-1, /) 替换

3.3 split(self, /, sep=None, maxsplit=-1) 拆分

3.4 partition(self, sep, /) 分区

3.5 expandtabs(self, /, tabsize=8) 扩充分隔符

3.6 join(self, iterable, /) 联接

3.7 center(self, width, fillchar=' ', /) 居中

3.8 ljust(self, width, fillchar=' ', /) 左对齐

3.9 rjust(self, width, fillchar=' ', /) 右对齐

4. 格式化输出个人信息


1. 一个简单(+-*/)的计算器

确保输入的都是数字(如果不是数字,让它重新输入)
输入格式必须是: 7+8 => 输出格式是 7 + 8 = 15

# str_data = 'a-8'
while True:
    str_data = str(input('请输入一个要计算的表达式:'))
    part_str = ()
    for operator in "+-*/":
        if operator in str_data:
            part_str = str_data.partition(operator)
            # print(part_str)
            # print(operator)
            break
    if part_str[0].isnumeric() & part_str[2].isnumeric():
        num1 = int(part_str[0])
        num2 = int(part_str[2])
        if operator == '+':
            print(num1, operator, num2, '=', num1 + num2)
        if operator == '-':
            print(num1, operator, num2, '=', num1 - num2)
        if operator == '*':
            print(num1, operator, num2, '=', num1 * num2)
        if operator == '/':
            print(num1, operator, num2, '=', num1 / num2)
    else:
        print('输入的不是数字,请重新输入')
        continue

2. while单层循环完成9 * 9乘法表
i = 1
j = 1
while i < 10:
    if j > i:   # 当j>i时,换行,i+1,并把j重置
        print()
        i += 1
        j = 1
        continue
    else:   # 当j<=i时,输出口诀,且不换行,j+1
        print(i, "*", j, "=", i*j, end="t")
        j += 1

3. str字符串中的方法的使用

3.1 strip(self, chars=None, /) 剥离

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

"""
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace removed.
 |      返回删除前导和尾随空格的字符串副本。
 |      If chars is given and not None, remove characters in chars instead.
        如果给定了chars而不是None,请删除chars中的字符
"""
str_data = "00000003210Runoob01230000000"
print(str_data.strip('0'))  # 3210Runoob0123
# 去除首尾字符 0
str2 = "   Runoob      "
# 去除首尾空格
print(str2.strip())  # Runoob

3.2 replace(self, old, new, count=-1, /) 替换

Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次
"""
 |  replace(self, old, new, count=-1, /)替换
 |      Return a copy with all occurrences of substring old replaced by new.
 |      返回一个副本,其中所有出现的子字符串旧替换为新
 |        count 计数
 |          Maximum number of occurrences to replace.
            要替换的最大出现次数
 |          -1 (the default value) means replace all occurrences.
            -1(默认值)表示替换所有引用。
 |      If the optional argument count is given, only the first count occurrences are replaced.
        如果给定了可选的参数计数,则只替换第一次出现的计数
"""
str_data = 'My name, My age, My money'
print(str_data.replace('My', 'You'))
print(str_data.replace('My', 'You', 2))

结果:

3.3 split(self, /, sep=None, maxsplit=-1) 拆分

Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串

  • str -- 分隔符,默认为所有的空字符,包括空格、换行(n)、制表符(t)等。
  • num -- 分割次数。默认为 -1, 即分隔所有。
"""
 |  split(self, /, sep=None, maxsplit=-1) 拆分
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      使用sep作为分隔符字符串,返回字符串中的单词列表。
 |      sep 分隔
 |        The delimiter according which to split the string.
            分割字符串所依据的分隔符。
 |        None (the default value) means split according to any whitespace,
            None(默认值)表示根据任何空格进行拆分
 |        and discard empty strings from the result.
            并从结果中丢弃空字符串。
 |      maxsplit 最大拆分
 |        Maximum number of splits to do.
            要执行的最大拆分数
 |        -1 (the default value) means no limit.
            |-1(默认值)表示没有限制。
"""
str_data = "123,123,123"
print(str_data.split(","))  # ['123', '123', '123']
print(str_data.split(',', 1))   # ['123', '123,123']

3.4 partition(self, sep, /) 分区

partition() 方法用来根据指定的分隔符将字符串进行分割。

如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

partition() 方法是在2.5版中新增的。

str : 指定的分隔符。

"""
 |  partition(self, sep, /) 分区
 |      Partition the string into three parts using the given separator.
 |      使用给定的分隔符将字符串分为三部分。
 |      This will search for the separator in the string.  If the separator is found,
        这将在字符串中搜索分隔符。如果找到分隔符,
 |      returns a 3-tuple containing the part before the separator, the separator
        返回一个3元组,其中包含分隔符之前的部分,分隔符它本身和它后面的部分。
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original string
        如果未找到分隔符,则返回包含原始字符串的3元组和两个空字符串。
 |      and two empty strings.
"""
str_data = '6+7'
print(str_data.partition('+'))  # ('6', '+', '7')

3.5 expandtabs(self, /, tabsize=8) 扩充分隔符

         expandtabs() 方法把字符串中的 tab 符号 t 转为空格,tab 符号 t 默认的空格数是 8,在第 0、8、16...等处给出制表符位置,如果当前位置到开始位置或上一个制表符位置的字符数不足 8 的倍数则以空格代替。

"""
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |      返回一个副本,其中所有制表符都使用空格展开。
 |      If tabsize is not given, a tab size of 8 characters is assumed.
        如果没有给出tabsize,则假设制表符大小为8个字符。
"""
print("123t123")   # 123 123
str_data = "123t123"
print(str_data.expandtabs())    # 123     123
print(str_data)     # 123 123
print(str_data.expandtabs(tabsize=2))   # 123 123

3.6 join(self, iterable, /) 联接

Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

  • sequence -- 要连接的元素序列。
"""
 |  join(self, iterable, /) 联接
 |      Concatenate any number of strings.
 |      串联任意数量的字符串
 |      The string whose method is called is inserted in between each given string.
        调用其方法的字符串插入到每个给定字符串之间。
 |      The result is returned as a new string.
 |      结果将作为新字符串返回。
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
"""
str_data = 'name'
# 序列:str、bytes、tuple、list
print(str_data.join(['a', 'b', 'c']))   # anamebnamec

3.7 center(self, width, fillchar=' ', /) 居中

Python center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。

  • width -- 字符串的总宽度。
  • fillchar -- 填充字符。
"""
 |  center(self, width, fillchar=' ', /)居中
        fillchar=' '表达式类型 /默认为空格 /用指定的值填充连续字节的数
 |      Return a centered string of length width.
 |      返回一个居中长度为width的字符串。
 |      Padding is done using the specified fill character (default is a space).
        使用指定的填充字符(默认为空格)填充。
"""
str_data = 'hello'
print(str_data.center(10, '*'))    # **hello***

3.8 ljust(self, width, fillchar=' ', /) 左对齐

ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

  • width -- 指定字符串长度。
  • fillchar -- 填充字符,默认为空格。
"""
 |  ljust(self, width, fillchar=' ', /) 左对齐
 |      Return a left-justified string of length width.
 |
 |      Padding is done using the specified fill character (default is a space).
"""
str_data = 'Alex'
print(str_data.ljust(10, '*'))  # Alex******

3.9 rjust(self, width, fillchar=' ', /) 右对齐

rjust() 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。

  • width -- 指定字符串长度。
  • fillchar -- 填充字符,默认为空格。
"""
 |  rjust(self, width, fillchar=' ', /) 右对齐
 |      Return a right-justified string of length width.
 |
 |      Padding is done using the specified fill character (default is a space).
"""
str_data = 'Alex'
print(str_data.rjust(10, '*'))  # ******Alex

4. 格式化输出个人信息

    姓名       年龄        性别        家庭住址
    xxx       xxxx
    list_data = [{name: xxx, age: xxx, gender: xxx, address}, .....]
    包含居中对齐,向左对齐, 向右对齐

"""
{:*^20}: ^居中对齐
{0:*<20}: <向左对齐
{name:*>20}: >向右对齐
"""
list_data = [{"name": "姓名", "sex": "性别", "age": "年龄", "address": "地址"},
             {'name': '张三', 'sex': '男生', 'age': 20, 'address': '陕西省汉中市洋县'},
             {'name': '李四', 'sex': '女生', 'age': 21, 'address': '陕西省西安市长安区'},
             {'name': '王五', 'sex': '男生', 'age': 22, 'address': '陕西省商洛市'}]
for i in range(0, len(list_data)):
    print('{0[name]:^10}{0[sex]:<10}{0[age]:>10}{0[address]:^20}'.format(list_data[i]))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991104.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号