注册 登录
编程论坛 Python论坛

變數可以自動給空值嗎?

Z89 发布于 2022-06-20 15:16, 1210 次点击
請問有方法當變數d與e是空值時,自動省略  d='' , e=''

當沒指定變數時 強制給予一個空值,  變數=''

讓程序能繼續執行



程序代码:
a= 'trans'
b= 'relating'
c= 'cause '
#d='' #空值
#
e='' #空值


y =  'yes '+a+' '+b+' '+c+' '+' '+d+' '+e
print(y)



[此贴子已经被作者于2022-6-20 15:19编辑过]

4 回复
#2
apull2022-06-21 09:58

y =  'yes '+a+' '+b+' '+c+(' '+d if('d' in vars ().keys()) else '' )+(' '+e if('e' in vars ().keys()) else '' )


[此贴子已经被作者于2022-6-21 10:01编辑过]

#3
Z892022-06-21 10:22
可以耶~感謝!!!  如果是下面這樣開怎麼改?

程序代码:
import re

def Matches(sstr,html,a,b):   
    lens=re.findall(sstr,html)   
    if len(lens)==0 or a >= len(lens):
       return False
    else:
       if b =="":
           return lens[a]
       else:   
           tr =   lens[a]
           if b >= len(tr):
              return False
           else:
              return tr[b]
      

html='''

https://11111gov.tw/888.aspx

https://22222gov.tw/777.aspx

https://33333gov.tw/666.aspx

'''


bdd = Matches ('(https.+)tw/(.+)',html,0,1) #有b參數

print(bdd)



bdd = Matches ('(https.+)tw',html,0) #沒b參數  所以不填

print(bdd)
#4
fall_bernana2022-06-21 11:30
以下是引用Z89在2022-6-21 10:22:48的发言:

可以耶~感謝!!!  如果是下面這樣開怎麼改?

import re

def Matches(sstr,html,a,b):   
    lens=re.findall(sstr,html)   
    if len(lens)==0 or a >= len(lens):
       return False
    else:
       if b =="":
           return lens[a]
       else:   
           tr =   lens[a]
           if b >= len(tr):
              return False
           else:
              return tr
      

html='''

https://11111gov.tw/888.aspx

https://22222gov.tw/777.aspx

https://33333gov.tw/666.aspx

'''


bdd = Matches ('(https.+)tw/(.+)',html,0,1) #有b參數

print(bdd)



bdd = Matches ('(https.+)tw',html,0) #沒b參數  所以不填
 
print(bdd)



你在函数直接赋一个默认值不就行了? def Matches(sstr,html,a,b=""):  
#5
sdg1232022-06-21 13:59
繁体字看着特别麻烦
1