Python,我可以在 if 语句中遍历列表吗?

Python, can I iterate through a list within an if statement?

我正在尝试根据用户输入 str (userInput) 编辑 str (myString)。已经有一组已知的子字符串,myString 可能包含也可能不包含,并被放入 str (namingConventionList) 列表中,如果在 myString 中使用了任何子字符串,则应替换为 userInput。如果使用 none 的命名约定集,我希望以几种不同的方式将 userInput 添加到 myString 中,具体取决于下划线 ("_") 是否存在以及在哪里。 有没有办法在 if 语句中遍历 namingConventionList?

        if myString.count(conv for conv in namingConventionList):
            myString= myString.replace(conv, userInput))
        elif userInput.startswith('_'):
            myString= '%s%s' % (name, userInput)
        elif userInputConvention.endswith('_'):
            myString= '%s%s' % (userInput, name)
        else:
            myString= '%s_%s' % (name, userInput)

我可能会这样处理你的问题:

for conv in namingConventionList:
    if conv in myString:
        myString = myString.replace(conv, userInput)
        break
else:
    if userInput.startswith('_'):
        myString= '%s%s' % (name, userInput)
    elif userInputConvention.endswith('_'):
        myString= '%s%s' % (userInput, name)
    else:
        myString= '%s_%s' % (name, userInput)
success = False
for conv in namingConventionList:
    if conv in myString:
        myString = myString.replace(conv, userInput)
        success = True

if not success:
    if userInput.startswith('_'):
        myString= '%s%s' % (name, userInput)
    elif userInputConvention.endswith('_'):
        myString= '%s%s' % (userInput, name)
    else:
        myString= '%s_%s' % (name, userInput)