简体   繁体   English

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

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

I am trying to edit a str (myString) based on user input str (userInput). 我正在尝试根据用户输入str(userInput)编辑一个str(myString)。 There are already a known set of subStrings that myString may or may not contain and are put into a list of str (namingConventionList) that, if any are used in myString should be replaced with userInput. 已经存在myString可能包含或可能不包含的一组已知子字符串,并将它们放入str(namingConventionList)列表中,如果在myString中使用了子字符串,则应将其替换为userInput。 If none of the set of naming conventions are used, I want the userInputadded to myString in a couple of different ways depending on if and where an underscore ("_") is. 如果没有使用任何一组命名约定,则我想通过下划线(“ _”)的位置和位置以几种不同的方式将userInput添加到myString上。 Is there a way to iterate through namingConventionList in an if statement? 是否可以通过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)

This is how I might approach your problem: 这就是我可能会解决您的问题的方式:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM