Reputation: 19379
A string can be with both single '_'
and double '__'
underscore characters at the end.
Checking it with :
if myString[-1]=='_': pass
works only for a single character. How to achieve the same using one line?
(only if last character(s)=='_' or '__').
Upvotes: 2
Views: 222
Reputation: 19379
Thanks for your suggestions. Here is how I ended up using it:
myString='asdfasdf.__'
invalid=['!','"','#','$','%','&','\\','(',')','*','+',',','-','.','/'
,':',';','<','=','>','?','@','[',"'",']','^','`','{','|','}','~',' ','_']
while myString and myString[-1] in invalid:
myString=myString.rstrip( invalid[ invalid.index(myString[-1]) ] )
Upvotes: 0
Reputation: 5069
How about this?
MyString0 = 'Hello'
MyString1 = 'Hello_'
MyString2 = 'Hello__'
MyString3 = 'Hello___'
f = lambda x : x.endswith(('_', '__')) and not x.endswith(('___'))
print f(MyString0) # --> False
print f(MyString1) # --> True
print f(MyString2) # --> True
print f(MyString3) # --> False
Upvotes: 0
Reputation: 2555
You can use regular expressions:
>>> re.match(".*[^_]__?$","test_")
<_sre.SRE_Match object; span=(0, 5), match='test_'>
>>> re.match(".*[^_]__?$","test__")
<_sre.SRE_Match object; span=(0, 6), match='test__'>
>>> re.match(".*[^_]__?$","test___")
None
Upvotes: 0
Reputation: 20581
If you cant make assumptions about the string length, a better way to check is
if len(myString)-len(myString.rstrip('_')) in (1,2):
#do something
Upvotes: 1
Reputation: 99680
For Python version > 2.5,
You can use endswith
with a tuple
underscores = ('_', '__')
if myString.endswith(underscores): pass
Demo
>>> underscores = ('_', '__')
>>> xx = "text__"
>>> xxx = "text_"
>>> xx.endswith(underscores)
True
>>> xxx.endswith(underscores)
True
>>>
Upvotes: 4
Reputation: 32197
If I understand you correctly, you can do that as:
if myString[-2:]=='__' or myString[-1] == '_':
#do something
Upvotes: 1