如果条件与字符

时间:2019-05-05 08:21:49

标签: python python-3.x

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

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)

3 个答案:

答案 0 :(得分:0)

最好只使用:

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)

答案 1 :(得分:0)

简单的解决方案

#! /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')]

答案 2 :(得分:0)

您的代码存在的问题是,您在for循环中定义了test_df = test.toPandas() ,因此循环每次运行都会覆盖存储在变量j=-1中的值。

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

j