我试图一次打印出一个字符串的三个字符。我知道
>>> s = 1234
>>> s[0:3]
123
我需要打印整个字符串,但一次只能显示三个字符。
这就是我的要求。编写一个PrintThree函数,一次打印出一个字符串s,三个字符。请记住,len(s)返回字符串的长度。
我只需要了解如何操作,如果你只是发布一个代码,请给出一个简短的解释,谢谢!
答案 0 :(得分:2)
假设我理解正确,它看起来像这样:
def PrintThree(s):
for i in range(0,len(s),3):
print s[i:i+3]
>>> PrintThree('abcd')
abc
d
>>> PrintThree('abgdag')
abg
dag
答案 1 :(得分:0)
有很多方法可以实现您的目标。我将采用最直接的方式
def printThrees(mystring):
s = '' # we are going to initialize an empty string
count = 0 # initialize a counter
for item in mystring: # for every item in the string
s+=item #add the item to our empty string
count +=1 # increment the counter by one
if count == 3: # test the value
print s # if the value = 3 print and reset
s = ''
count = 0
return
mystring = '123abc456def789'
printThrees(mystring)
123
abc
456
def
789
答案 2 :(得分:0)
我只需要了解如何操作
切片索引是整数。
len(s)
会给你一个整数字符串的长度。
您可以使用for
循环来增加整数。