Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/13.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
拆下第二个&x27;o';从语句';helloworld';用python_Python_Replace_Continue - Fatal编程技术网

拆下第二个&x27;o';从语句';helloworld';用python

拆下第二个&x27;o';从语句';helloworld';用python,python,replace,continue,Python,Replace,Continue,python初学者: for l in 'helloworld': if l == 'w': continue lnew = l lnew = ''.join(lnew).replace('o', '').split() print "The letter is", lnew 我试图从'helloworld'中删除字母'w'后的字母'o'。我知道continue语句将控件返回到while循环的开头。但是我如何确保它在运行时跳过字母'w'之后的'o

python初学者:

for l in 'helloworld':
    if l == 'w':
        continue
    lnew = l
    lnew = ''.join(lnew).replace('o', '').split()
    print "The letter is", lnew
我试图从'helloworld'中删除字母'w'后的字母'o'。我知道continue语句将控件返回到while循环的开头。但是我如何确保它在运行时跳过字母'w'之后的'o'

我本来可以做的,但那会破坏学习的目的

相反,我尝试创建一个新的列表,其中它将用“”(空白)替换字母'o',然后拆分列表,但它同时替换了'o',如下所示:

The letter is ['h']
The letter is ['e']
The letter is ['l']
The letter is ['l']
The letter is []
The letter is []
The letter is ['r']
The letter is ['l']
The letter is ['d']
在continue语句跳过字母“w”之后,我应该如何做才能删除字母“w”之后的字母“o”(答案应该是这样的)


我希望我能理解你的意思。我稍微修改了代码:

string = 'helloworld'
new_string = ''

is_second_o = False

for char in string:
    if char == 'o':
        if not is_second_o:
            new_string += char
        is_second_o = True
    else:
        new_string += char


print new_string
输出:

hellowrld
所以我所做的是迭代字符串,检查当前字符是否为'o',如果是-我使用布尔标志检查它是否是第一个

如果当前字符不是'o',只需将其附加到新的\u字符串中即可

另一种方法:

w_found = False
for l in 'helloworld':
    if l == 'w':
        w_found = True
    if w_found and l == 'o': # skip this o as it comes after w
        continue
    print "The letter is", l
这张照片是:

The letter is h
The letter is e
The letter is l
The letter is l
The letter is o
The letter is w
The letter is r
The letter is l
The letter is d

可以使用string.rindex查找最右边的o。还有其他选择: 如果我们找不到'o'值,则会引发错误,我们将通过使str2与str1相同

str1 = 'helloworld'
str2 = str1
try:
    idx = str1.rindex('o')
    str2=str1[:idx] + str1[idx+1:]
except ValueError:
    pass
print "\n".join(str2)
输出
可能不是练习的目的,只是好奇:

'o'.join(term.replace('o', '') for term in 'helloworld'.split('o', 1))

你说的移除是什么意思?你的意思是不打印还是“创建一个没有o的新字符串”?
h
e
l
l
o
w
r
l
d
'o'.join(term.replace('o', '') for term in 'helloworld'.split('o', 1))