Python - 从项目的第一个实例开始打印字符串中的所有项目
Python - Print all items in a string from first instance of item onwards
我想按顺序打印所有项目,从特定项目的第一个实例开始。
为此,我不能使用查找或索引。我被特别要求使用 '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
O.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
我想按顺序打印所有项目,从特定项目的第一个实例开始。 为此,我不能使用查找或索引。我被特别要求使用 '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
O.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