0

I am trying to edit a str (myString) based on user input str (userInput). 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. 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. Is there a way to iterate through namingConventionList in an if statement?

        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)
rasonage
  • 53
  • 1
  • 1
  • 9

2 Answers2

0

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)
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • This is the first time I've seen that [`for..else` construction](http://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops). Neat. – TigerhawkT3 Apr 30 '15 at 03:45
0
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)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97