Python 如何从字符串中间获取2个字符? 导入时间 日期=时间。strftime(“%d:%m:%y”) 打印日期#返回“18:05:14” 打印日期[-2:]#返回'14' 打印日期[:2]#返回“18” #打印

Python 如何从字符串中间获取2个字符? 导入时间 日期=时间。strftime(“%d:%m:%y”) 打印日期#返回“18:05:14” 打印日期[-2:]#返回'14' 打印日期[:2]#返回“18” #打印,python,string,character,Python,String,Character,指定开始和停止位置: >>> date = '18:05:14' >>> date[3:5] '05' >>> [3:5]将获取从索引3到索引5独占的每个字符。获取值的方法很多 print(date[3:5]) # 05 (start the 4th to 5th char) print(date.split(":")[1]) # 05 (split string and get 2nd string) 你们太棒了。

指定开始和停止位置:

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

[3:5]
将获取从索引
3
到索引
5
独占的每个字符。

获取值的方法很多

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

你们太棒了。非常感谢。如果您有一个较长的字符串,并且在末尾附近需要一些字符,您可以使用负数从末尾开始计数。例如,
date[-5:-3]
返回
'05'
你们真是太棒了。非常感谢。