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