Python 如何从字符串的中间获取 2 个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23728590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get 2 characters from the middle of a string?
提问by Peaser
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'
How can I (preferably) use the [:number:] thing to look for the 4th and 5th character ONLY of "18:05:14" (05)? if i can't use [:#], that's fine. I can't find any possible way, but any help is appreciated.
我如何(最好)使用 [: number:] 东西来查找“18:05:14”(05)的第 4 个和第 5 个字符?如果我不能使用 [:#],那也没关系。我找不到任何可能的方法,但任何帮助表示赞赏。
采纳答案by Peaser
Specify a start and stop position:
指定开始和停止位置:
>>> date = '18:05:14'
>>> date[3:5]
'05'
>>>
[3:5]
will get every character from index 3
inclusive to index 5
exclusive.
[3:5]
将获取从3
包含索引到5
不包含索引的每个字符。
回答by Puffin GDI
You have many ways to get value.
您有多种获取价值的方法。
print(date[3:5]) # 05 (start the 4th to 5th char)
print(date.split(":")[1]) # 05 (split string and get 2nd string)