2011-08-08 7 views
15

मैं कुछ पाइथन को बनाए रखने/अपडेट/पुनः लिखने/ठीक करने की कोशिश कर रहा हूं जो इस तरह थोड़ा दिखता है:पायथन में आउटपुट स्वरूपण: एक ही चर के साथ कई% s को बदलना

variable = """My name is %s and it has been %s since I was born. 
       My parents decided to call me %s because they thought %s was a nice name. 
       %s is the same as %s.""" % (name, name, name, name, name, name) 

छोटे स्निपेट हैं जो इस स्क्रिप्ट पर इस तरह दिखते हैं, और मैं सोच रहा था कि क्या है इस कोड को लिखने के लिए एक सरल (अधिक पायथनिक?) तरीका। मुझे इसका एक उदाहरण मिला है जो उसी वैरिएबल को लगभग 30 गुना बदल देता है, और यह सिर्फ बदसूरत लगता है।

एकमात्र तरीका है (मेरी राय में) कुटिलता इसे बहुत कम बिट्स में विभाजित करने के लिए?

variable = """My name is %s and it has been %s since I was born.""" % (name, name) 
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name) 
variable += """%s is the same as %s.""" % (name, name) 

उत्तर

47

पर एक नजर है।

var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' } 

या format स्पष्ट संख्या के साथ।

var = '{0} {0} {0}'.format('look_at_meeee') 

ठीक है, या format नामित पैरामीटर के साथ।

var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy') 
+3

आपका अंतिम विकल्प खूबसूरती से पढ़ता है, बहुत बहुत धन्यवाद - बस मुझे पाइथन से क्या उम्मीद है! – alexmuller

5

उपयोग नई string.format:

name = 'Alex' 
variable = """My name is {0} and it has been {0} since I was born. 
      My parents decided to call me {0} because they thought {0} was a nice name. 
      {0} is the same as {0}.""".format(name) 
5
>>> "%(name)s %(name)s hello!" % dict(name='foo') 
'foo foo hello!' 
2
variable = """My name is {0} and it has been {0} since I was born. 
       My parents decided to call me {0} because they thought {0} was a nice name. 
       {0} is the same as {0}.""".format(name) 
3

उपयोग स्वरूपण तार:

>>> variable = """My name is {name} and it has been {name} since...""" 
>>> n = "alex" 
>>> 
>>> variable.format(name=n) 
'My name is alex and it has been alex since...' 

भीतर पाठ {} की जानकारी देता या एक सूचकांक मान हो सकता है ।

एक और फैंसी चाल ** ऑपरेटर के साथ संयोजन में एकाधिक चर परिभाषित करने के लिए एक शब्दकोश का उपयोग करना है।

>>> values = {"name": "alex", "color": "red"} 
>>> """My name is {name} and my favorite color is {color}""".format(**values) 
'My name is alex and my favorite color is red' 
>>> 
संबंधित मुद्दे