【问题标题】:How can I get 2 characters from the middle of a string?如何从字符串中间获取 2 个字符?
【发布时间】:2014-05-19 01:35:27
【问题描述】:
import time

date = time.strftime("%d:%m:%y")


print date #returns '18:05:14'

print date[-2:] #returns '14'

print date[:2] #returns '18'

#print ??? <-returns '05'

我如何(最好)使用 [:number:] 来查找“18:05:14”(05)的第 4 和第 5 个字符?如果我不能使用 [:#],那很好。我找不到任何可能的方法,但感谢任何帮助。

【问题讨论】:

    标签: python string character


    【解决方案1】:

    指定开始和停止位置:

    >>> date = '18:05:14'
    >>> date[3:5]
    '05'
    >>>
    

    [3:5] 将从索引 3 包含到索引 5 排除每个字符。

    【讨论】:

    • 你们太棒了。谢谢!
    • 如果您有一个较长的字符串并且需要一些接近末尾的字符,您可以使用负数从末尾开始计数。前任。 date[-5:-3] 返回'05'
    【解决方案2】:

    你有很多获得价值的方法。

    print(date[3:5])           # 05 (start the 4th to 5th char)
    print(date.split(":")[1])  # 05 (split string and get 2nd string)
    

    【讨论】:

    • 你们太棒了。谢谢!
    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多