跟我学python(5)- 匹配数字
1. 程序要求读取输入的字符串,是否是数字;转换为浮点数并输出。2. 所需方法1)raw_inputraw_input([prompt])2)re.matchre.match(pattern, string, flags=0)3)类型转换(1)字符串转浮点float(x)(2)数字转字符串str(x)3. 源代码#coding=utf-8'''Created on 2019年1月3日@author
·
1. 程序要求
读取输入的字符串,是否是数字;
转换为浮点数并输出。
2. 所需方法
1)raw_input
raw_input([prompt])
2)re.match
re.match(pattern, string, flags=0)
3)类型转换
(1)字符串转浮点
float(x)
(2)数字转字符串
str(x)
3. 源代码
#coding=utf-8
'''
Created on 2019年1月3日
@author: xiaobin
'''
import re
'''
#mre22_1.pl
#! /usr/bin/perl -w
# Mastering Regular Expressiona: Chapter 2 Section 2.
# first program
print "Enter a temperature in Celsius:\n";
$celsius = <STDIN>;
chomp($celsius);
if ( $celsius =~ /^[0-9]+$/) {
$fahrenheit = ($celsius * 9 / 5) + 32;
print "$celsius C is $fahrenheit F\n";
}
else {
print "Expecting a number, so I don't understand \"$celsius\".\n";
}
'''
str1 = raw_input("Enter a temperature in Celsius: ")
res = re.match('^[0-9]+$', str1)
if res :
celsius = float(str1)
fahrenheit = (celsius * 9 / 5) + 32
print(str1 + "C is " + str(fahrenheit) + "F")
else :
print("Expecting a number, so I don't understand " + '\"' + str1 + '\"')
run:
Enter a temperature in Celsius: 38
38C is 100.4F
Reference:
1. python files io
2. search vs match
3. python numbers
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)