xiaobin_hlj80

https://blog.csdn.net/xiaobin_HLJ80 http://blog.chinaunix.net/uid/31552151.html

导航

跟我学python(5)- 匹配数字

读取输入的字符串,是否是数字;

转换为浮点数并输出。

raw_input

input([prompt])

re.match

re.match(pattern, string, flags=0)

类型转换

  • (1)字符串转浮点
float(x) 
  • (2)数字转字符串
str(x)

代码

#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: ") # python 2
str1 = 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 + '\"')

output:

Enter a temperature in Celsius: 38
38C is 100.4F

Reference:

  1. python files io
  2. search vs match
  3. python numbers

posted on 2026-02-03 16:08  xiaobin80  阅读(0)  评论(0)    收藏  举报