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

本文详细介绍了如何使用Python的raw_input和re.match方法读取输入的字符串判断是否为数字,并将其转换为浮点数进行输出。通过实际代码演示,深入理解字符串到数字的类型转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值