Python,每次打印字符串中的特定字符数量

-4 投票
3 回答
10059 浏览
提问于 2025-04-18 04:41

我想一次打印出字符串中的三个字符。我知道

>>> s = 1234
>>> s[0:3]
123 

我需要打印整个字符串,但每次只显示三个字符。

这是我被要求做的。写一个函数 PrintThree(s),它每次打印字符串 s 中的三个字符。记住,len(s) 可以返回字符串的长度。

我只是需要一些指导,如果你只发代码,请简单解释一下,谢谢!

3 个回答

0

我只是需要一些指导,告诉我该怎么做。

切片的索引是整数,也就是说你用来选择字符串部分的位置是用数字来表示的。

len(s) 这个命令可以告诉你一个字符串的长度,结果是一个整数。

你可以用 for 循环来让一个整数逐渐增加,也就是可以让数字一个一个往上加。

3

假设我理解得没错,情况看起来是这样的:

def PrintThree(s):
    for i in range(0,len(s),3):
        print s[i:i+3]

>>> PrintThree('abcd')
    abc
    d

>>> PrintThree('abgdag')
    abg
    dag
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

撰写回答