带字符的条件

2024-05-23 14:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

如何检查字符串中的一个字符是否等于另一个字符?在我下面的示例中,应该找到字符串中字符的位置,但我的第一个方法不起作用。为什么?你知道吗

txt = "Hello World"
CharacterToFind = 'W'
#returns position of first appearance of charater in string
#returns -1 if character is not found

#this does not work:
for k in range(len(txt)): 
    print(k, txt[k])
    j=-1
    if(txt[k] == CharacterToFind): #this line likely contains the error
        j=k
print(j)

#this works:
l=txt.find(CharacterToFind)
print(l)

Tags: of方法字符串intxt示例helloworld
3条回答

代码的问题是在for循环中定义了j=-1,因此每次循环运行时都会覆盖存储在变量j中的值。你知道吗

解决方案是在循环外定义j,如下所示:

txt = "Hello World"
CharacterToFind = 'W'
j = -1
for k in range(len(txt)): 
    print(k, txt[k])
    if(txt[k] == CharacterToFind):
        j=k
print(j)

最好只使用:

print(txt.find(char_to_find))

但是如果你想用一个循环来练习,这是一个很好的方法:

txt = "Hello World"
char_to_find = 'W'

for i, char in enumerate(txt):
    if char == char_to_find:
        print(i)
        break
else:
    # will run if loop didn't break
    print(-1)

简单的解决方案

#! /usr/bin/python3


txt = "Hello World"
CharacterToFind = 'W'

for index, character in enumerate(txt):
    if character == CharacterToFind:
        print(index, character)
        break


for index in range(len(txt)):
    if txt[index] == CharacterToFind:
        print(index, txt[index])
        break

if CharacterToFind in txt:
    print(CharacterToFind)


基于功能的解决方案:

#! /usr/bin/python3

txt = "Hello World"
CharacterToFind = 'W'


def try_to_find(CharacterToFind, txt):
    for index in range(len(txt)):
        if txt[index] == CharacterToFind:
            return (index, txt[index])
    return -1


result = try_to_find(CharacterToFind, txt)
if result:
    print(result)

查找列表中所有匹配项的更复杂的解决方案。也是理解yield的好例子

#! /usr/bin/python3

txt = "Hello World"
CharacterToFind = 'o'


def try_to_find_v1(CharacterToFind, txt):
    for index in range(len(txt)):
        if txt[index] == CharacterToFind:
            yield (index, txt[index])
    yield -1

results = []
find_gen = try_to_find_v1(CharacterToFind, txt)
while True:
    res = next(find_gen)
    if res == -1:
        break
    else:
        results.append(res)

print("\nv1")
if len(results) > 0:
    print(results)
else:
    print(-1)


def try_to_find_v2(CharacterToFind, txt):
    for index in range(len(txt)):
        if txt[index] == CharacterToFind:
            yield (index, txt[index])


results = []
find_gen = try_to_find_v2(CharacterToFind, txt)
while True:
    try:
        results.append(next(find_gen))
    except StopIteration:
        break

print("\nv2")
if len(results) > 0:
    print(results)
else:
    print(-1)

输出:

v1
[(4, 'o'), (7, 'o')]

v2
[(4, 'o'), (7, 'o')]

相关问题 更多 >