Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...