Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

python - Using startswith() but doesn't contain the specified element

I currently want my program to deal with string depending on what they contain:

if x.startswith("_") and "_" in x:
            split_items = x.split("_")
            convert_to_uppercase = [a.upper() for a in split_items]
            split_items = [change.capitalize() for change in split_items]
            final_items.append('_'.join(split_items))
            
        
        elif not x.startswith("_") and not "_" in x:
            final_items.append(x)
            
        elif x.startswith("_") and not "_" in x:
            final_items.append(x)

So for example I want _hellothere, _hello_there and hellothere to be processed differently, is that possible using the existing if statements?

question from:https://stackoverflow.com/questions/65939238/using-startswith-but-doesnt-contain-the-specified-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you should use x[1:] to check remaining elements in that string

list1 = ['_hellothere', '_hello_there', 'hellothere']
final_items = []
for x in list1:
  if x.startswith("_") and "_" in x[1:]:
      split_items = x.split("_")
      convert_to_uppercase = [a.upper() for a in split_items]
      split_items = [change.capitalize() for change in split_items]
      final_items.append('_'.join(split_items))
      
  elif not x.startswith("_") and not "_" in x[1:]:
      final_items.append(x)
      
  elif x.startswith("_") and not "_" in x[1:]:
      final_items.append(x)

print(final_items)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...