Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—从项目的第一个实例开始,以字符串形式打印所有项目_Python_String_Instance - Fatal编程技术网

Python—从项目的第一个实例开始,以字符串形式打印所有项目

Python—从项目的第一个实例开始,以字符串形式打印所有项目,python,string,instance,Python,String,Instance,我想以特定项目的第一个实例开始的顺序打印所有项目。 为此,我不能使用find或index。我被特别要求使用'for'语句、linenum(字符串中项目的位置)、length(字符串的长度)和count(特定字符在字符串中出现的次数)的组合 到目前为止,我已经- def PrintFrom(c,s): count = 0 for item in s: if item == c: count +=1 if count > 0:

我想以特定项目的第一个实例开始的顺序打印所有项目。 为此,我不能使用find或index。我被特别要求使用'for'语句、linenum(字符串中项目的位置)、length(字符串的长度)和count(特定字符在字符串中出现的次数)的组合

到目前为止,我已经-

def PrintFrom(c,s):
    count = 0
    for item in s:
        if item == c:
           count +=1
    if count > 0:
        print (item)
我要找的是:

PrintFrom("x","abcxdef")
->x
->d
->e
->f

如果有人能帮助我,我将不胜感激。谢谢。

以下是如何使用for循环完成此操作

def PrintFrom(c, s):
    for i, ch in enumerate(s):
        if ch == c:
            return '\n'.join(list(s[i:]))
print PrintFrom('x', 'abcxdef')
下面是如何使用递归实现它

def PrintFrom(c, s, p = 0):
    if s[p] == c:
        return '\n'.join(list(s[p:]))
    return PrintFrom(c, s, p + 1)
print PrintFrom('x', 'abcxdef')

如果您的模式只有一个字符长度

def print_from(start, my_string):
  _print = False
  for ch in my_string:
    if ch == start:
      _print = True
    if _print:
      print(ch)

你几乎完全正确。将第二条if语句缩进到与第一条if语句相同的级别,代码就可以运行了。目前,第二个if语句仅在for循环结束后出现,这意味着在遇到项时打印它们已经太晚了

def PrintFrom(c,s):
    count = 0
    for item in s:
        if item == c:
           count +=1
        if count > 0: # indented to be inside of for-loop
           print (item)
进行修改后运行:

>>> PrintFrom("x","abcxdef")
x
d
e
f

Ps代码在适当的缩进和冒号下工作良好

def PrintFrom(c,s):
    count = 0
    for item in s:
        if item == c:
           count +=1
        if count > 0:
           print (item)

PrintFrom("x","asdxfgh")
输出: x F G
h

@NightShadeQueen我认为你的谓词是错误的,应该是
x!=c
?@wilbur是的,我打过了,谢谢!在我看来,这很好-您的代码在运行时当前输出什么?投票关闭,直到您提供当前输出以及它与您想要的不同。编辑-无所谓,只是看到了问题。史蒂文是对的。@StevenRumbalski非常感谢你,它现在运行得很好。没错,但是考虑到六分钟前发布的另外两个答案也指出了这一点,你比赛有点晚了。