如何获取字符串的一部分并将其传递给python中的其他函数? [英] How to get part of string and pass it to other function in python?
问题描述
我的任务是验证字符串是否为有效的日期和时间.
My task is to verify whether string is valid date and time or not.
"2013-01-01W23:01:01"
"2013-01-01W23:01:01"
日期和时间用符号"W"或空格分隔.
如何获取字符串的第一部分"2013-01-01"并将其传递给函数valid_date(value)
,并将第二部分"23:01:01"传递给其他函数valid_time(value)
我尝试过:
The date and the time are separated with the symbol 'W' or white space.
How can I get the first part of the string - "2013-01-01" and pass it to function valid_date(value)
and the second part '23:01:01' to other function valid_time(value)
I tried:
def is_datetime(value):
if(value.find[' '] >= 0):
return is_date(value[:value.find[' '] - 1]) and is_time(value[value.find[' '] + 1:])\
但是显然我不允许这样做吗?
but apparently I am not allowed to do that ?
推荐答案
使用 str.partition()
快速获得第一部分:
Use str.partition()
to get the first part, fast:
value.partition('W')[0]
您也可以将 str.split()
用于Python版本< 2.5.将拆分限制为仅第一个W
:
value.split('W', 1)[0]
即使value
中没有'W'
字符,这两种技术都将始终产生结果.
Either technique will always yield a result, even if there is no 'W'
character in value
.
演示:
>>> value = "2013-01-01W23:01:01"
>>> value.partition('W')[0]
'2013-01-01'
>>> value.split('W', 1)[0]
'2013-01-01'
这篇关于如何获取字符串的一部分并将其传递给python中的其他函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!