RDTJr
RDTJr

Reputation: 215

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?

Upvotes: 0

Views: 175

Answers (3)

jjoy
jjoy

Reputation: 172

If you're trying to have _hellothere, _hello_there and hellothere be processed differenty this should work.

if x.startswith("_") and "_" not in x[1:]:
    #Proccess for _hellothere

elif not x.startswith("_") and not "_" in x:
    #Process for hellothere

elif x.startswith("_") and "_" in x[1:]:
    #Process for _hello_there

I hope this may be of help.

Upvotes: 1

Prakash Dahal
Prakash Dahal

Reputation: 4875

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)

Upvotes: 0

Ismail Hafeez
Ismail Hafeez

Reputation: 740

First of all, as @chepner said, if x starts with ' _ ' then ' _ ' obviously exists in x. So if you remove the ' _ ' exists in x it would be better.

Secondly,

'_hellothere' should pass through the first if statement.

'hellothere' should pass through the first elif statement.

However, for '_hello_there' it should pass through the first if statement again. If you want a different output for it then try:

elif x.startswith("_") and x.count("_") > 1:
    # Do something

Here it checks if it starts with ' _ ' and then counts the number of ' _ ' in x and if its greater than 1, it executes.

If this answer helped, kindly upvote and mark as correct. Appreciate it!

Upvotes: 0

Related Questions