[英]How to filter and format the data from input function in Python?
When I define a struct in C, I can use the scanf
function to get and format the data from standard input. 在C语言中定义结构时,可以使用scanf
函数从标准输入中获取数据并设置其格式。
For example: 例如:
struct date { int day; int month; int year;};
struct date today;
scanf("%i/%i/%i", &today.day, &today.month, &today.year)
But how could I get the same function in Python if I have already define a new class? 但是,如果已经定义了一个新类,如何在Python中获得相同的功能? I have tried to compose a code but it's too long. 我试图编写代码,但是太长了。 Could you please introduce a simple way? 您能介绍一个简单的方法吗?
Code: 码:
class Date(object):
def __init__(self, day=None, month=None, year=None):
self.day = day
self.month = month
self.year = year
val = raw_input("Enter date in day/month/year format: ")
vals = val.split("/")
today = Date(*vals)
print "{}/{}/{}".format(today.day, today.month, today.year)
Gives: 得到:
% python filterformat.py
Enter date in day/month/year format: 14/02/2016
14/02/2016
Python comes with bells and whistles, use them: Python带有钟声和口哨声,请使用它们:
import datetime as dt
# input for python3, raw_input for python2
datestr = input('Please enter a date using this format: %d/%m/%Y')
date = dt.date.strptime(datestr, format='%d/%m/%Y')
print('You entered {:%d/%m/%Y}'.format(date))
See the datetime docs for more info: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior 有关更多信息,请参见datetime文档: https : //docs.python.org/2/library/datetime.html#strftime-strptime-behavior
You can use the dateparser module. 您可以使用dateparser模块。 From the docs: 从文档:
This will try to parse a date from the given string, attempting to detect the language each time. 这将尝试从给定的字符串解析日期,并尝试每次检测该语言。
The parse
function will parse almost any standard date format, and return a datetime object from a given string, where datetime is standard and built into python. parse
函数将解析几乎所有标准日期格式,并从给定的字符串返回datetime对象,其中datetime是标准的并内置在python中。
Usage for date input from user: 用户输入日期的用法:
import dateparser
date_from_user=input('Enter a date')
datetime_obj=dateparser.parse(date_from_user)
print(datetime_obj.year, datetime_obj.month, datetime_obj.day)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.