Python基础(数字,字符串方法)
数字:
1 #二进制转十进制 2 a='100' 3 v=int(a,base=2) 4 print(v)
1 #当前数字的二进制至少有多少位 2 b=2 3 v2=b.bit_length() 4 print(v2)
字符串:
1 #首字母大写 2 a="kelvin" 3 v=a.capitalize() 4 print(v)
1 #终极无敌'大写'变'小写'---->casefold 2 b="KELVIN" 3 v1=b.casefold() 4 v2=b.lower() 5 print(v1) 6 print(v2)
1 #居中显示字符串 2 c="kelvin" 3 v3=c.center(50,"-") #第二个参数不填,默认空格 4 print(v3)
1 #查询在字符串中指定序列出现次数 2 d="kelvinvinkddq" 3 num=d.count("d") 4 print(num)
1 #判断是否以指定字符序列开头或者结尾 2 e="nihaoyahahakelvin" 3 v4=e.endswith("in") 4 v6=e.endswith("o") 5 v5=e.startswith("ni") 6 v7=e.startswith("ll") 7 print(v4) 8 print(v6) 9 print(v5) 10 print(v7)
1 #查找字符串中是否有指定序列 2 f="fsdhjheujfdkelvinvfs d" 3 num1=f.find("kelvin") 4 num2=f.find("fsdf") 5 print(num1) 6 print(num2)
1 #字符串格式化 2 g="i am {name},age {age}" 3 v8=g.format(name="alex",age=19) 4 v9=g.format_map({"name":"kelvin","age":21}) 5 print(v8) 6 print(v9)
1 #返回指定序列索引,不存在则报错 2 a="kelvinalapplebanag" 3 v=a.index("w") 4 print(v)
1 str = "this2009"; # 字符中没有空格 2 print (str.isalnum()); 3 4 str = "this is string example....wow!!!"; 5 print(str.isalnum());
1 str = "this"; # No space & digit in this string 2 print str.isalpha(); 3 4 str = "this is string example....wow!!!"; 5 print str.isalpha();
1 str = "123456"; # Only digit in this string 2 print str.isdigit(); 3 4 str = "this is string example....wow!!!"; 5 print str.isdigit();
1 str = " "; 2 print str.isspace(); 3 4 str = "This is string example....wow!!!"; 5 print str.isspace();
1 tr = "This Is String Example...Wow!!!"; 2 print str.istitle(); 3 4 str = "This is string example....wow!!!"; 5 print str.istitle();
1 str = "-"; 2 seq = ("a", "b", "c"); # 字符串序列 3 print str.join( seq );
1 str = "this is string example....wow!!!"; 2 3 print str.ljust(50, '0');
1 str = " this is string example....wow!!! "; 2 print str.lstrip(); 3 str = "88888888this is string example....wow!!!8888888"; 4 print str.lstrip('8');
1 from string import maketrans # 必须调用 maketrans 函数。 2 3 intab = "aeiou" 4 outtab = "12345" 5 trantab = maketrans(intab, outtab) 6 7 str = "this is string example....wow!!!"; 8 print str.translate(trantab); 9 10 以上实例输出结果如下: 11 12 th3s 3s str3ng 2x1mpl2....w4w!!!
1 str = "this is really a string example....wow!!!"; 2 print "Max character: " + max(str); 3 4 str = "this is a string example....wow!!!"; 5 print "Max character: " + max(str);
1 2 str = "00000003210Runoob01230000000"; 3 print str.strip( '0' ); # 去除首尾字符 0 4 5 6 str2 = " Runoob "; # 去除首尾空格 7 print str2.strip();
1 str = "this is string example....wow!!!"; 2 print str.swapcase(); 3 4 str = "THIS IS STRING EXAMPLE....WOW!!!"; 5 print str.swapcase();
以上是经常使用的内置方法。