python中数字转换成字符串

时间:2021-12-16 01:26:00

一、数字转成字符串,使用格式化字符串:

tt=322

tem='%d' %tt

tem即为tt转换成的字符串

常用的格式化字符串:

%d            整数

%f%F        浮点数

%e%E       科学计数

%g%G        e 和%f/%E 和%F 的简写 

%%              输出%

格式化操作符辅助指令 

符号                作用 

*            定义宽度或者小数点精度 

-            用做左对齐 

+              在正数前面显示加号( + ) 

<sp>          在正数前面显示空格 

#           在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X') 

0             显示的数字前面填充‘0’而不是默认的空格 

%            '%%'输出一个单一的'%' 

(var)       映射变量(字典参数) 

m.n          m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) 

示例:

'%f' % 1234.567890     输出:'1234.567890'

'%.2f' % 1234.567890   输出:'1234.57'


原文地址:

http://edu.codepub.com/2010/1025/26632.php

 

随机整数:

>>> import random >>> random.randint(0,99) 21   随机选取0到100间的偶数: >>> import random >>> random.randrange(0, 101, 2) 42   随机浮点数: >>> import random >>> random.random()  0.85415370477785668 >>> random.uniform(1, 10) 5.4221167969800881   随机字符: >>> import random >>> random.choice('abcdefg&#%^*f') 'd'   多个字符中选取特定数量的字符: >>> import random random.sample('abcdefghij',3)  ['a', 'd', 'b']   多个字符中选取特定数量的字符组成新字符串: >>> import random >>> import string >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r eplace(" ","") 'fih'   随机选取字符串: >>> import random >>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ) 'lemon'   洗牌: >>> import random >>> items = [1, 2, 3, 4, 5, 6] >>> random.shuffle(items) >>> items [3, 2, 5, 6, 4, 1]