Python格式化字符串(f,F,format,%),,# 格式化字符串:


# 格式化字符串: 在字符串前加上 f 或者 F 使用 {变量名} 的形式来使用变量名的值year = 2020event = ‘Referendum‘value = f‘Results of the {year} {event}‘print(f‘Results of the {year} {event} \n‘, value)# : .3f 标示 保留前面的变量值/字面值3位小数 , 3d, 3 则是让盖子段成为最小字符宽度,在使列对齐时作用大print(f‘The value of pi is approximately {3.1415926:.3f}.‘)print(f‘The value of pi is approximately {31415926: 3d}.‘)print(F‘The value of pi is approximately {3.1415926: 3}.‘)# str.format 格式化字符串 # 索引形式,对号入座print(‘The value of pi is approximately {0}.‘.format(‘哈哈‘))# 关键字形式print(‘The value of pi is approximately {name}.‘.format(name=‘jobi‘))# %格式化字符串(旧) %5.3f 总长度5 保留3位小数print(‘The value of pi is approximately %5.3f.‘ % 3.141592678)# repr()  str() 函数 将对象转换为 字符串f1 = 22.3print(type(repr(f1)))# str.rjust(空格数量) 在字符串左侧填充空格for x in range(1, 11):    print(repr(x), str(x * x).rjust(4), end=‘\n‘)# str.ljust(空格数量) 在字符串右侧填充空格for x in range(1, 11):    print(repr(x), str(x * x).ljust(4), end=‘\n‘)# str.center(空格的总数量), 在字符串中间 填充 总数量/2 字符串末尾 填充 总数量/2 空格for x in range(1, 11):    print(repr(x), str(x * x).center(4), end=‘\n‘)      # 10 100# str.zfill(字符串总长度)  左侧填充零 的数量为  填充后的长度 - 填充前的长度print(‘12‘.zfill(3))    # 012

内容摘自官网:https://docs.python.org/zh-cn/3.7/tutorial/inputoutput.html#the-string-format-method

Python格式化字符串(f,F,format,%)

评论关闭