for peoject in subjects:
try:
peoject_name = peoject.content
print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1]))
except IndexError:
print("this line doesn't have a -")
x = 'hello-test'
print(x.split('-')[1]) # test
print(x.split('-')[-1]) # test
y = 'hello'
print(y.split('-')[-1]) # hello
print(y.split('-')[1] if len(y.split('-'))>=2 else y) # hello
print(y.split('-')[1] if len(y.split('-'))>=2 else '') # [empty string]
您只需检查
peoject_name
中是否有'-'
:您有几个选项,这取决于在没有连字符的情况下要执行的操作。在
或者选择split via
[-1]
中的最后一项,或者使用三元语句应用替代逻辑。在相关问题 更多 >
编程相关推荐