2012-04-09 10 views
7

मुझे एक स्ट्रिंग में वर्णों की एक निश्चित मात्रा के बाद एक जगह डालने की आवश्यकता है। टेक्स्ट एक वाक्य है जिसमें कोई रिक्त स्थान नहीं है और इसे प्रत्येक एन अक्षरों के बाद रिक्त स्थान के साथ विभाजित करने की आवश्यकता है।पायथन का उपयोग कर स्ट्रिंग में कुछ निश्चित वर्णों के बाद मैं एक स्पेस कैसे डालूं?

तो यह ऐसा कुछ होना चाहिए।

thisisarandomsentence 

और मैं इसे के रूप में वापसी करना चाहते हैं:

this isar ando msen tenc e 

समारोह है कि मैं है:

def encrypt(string, length): 

वहाँ वैसे भी अजगर पर यह करने के लिए है?

+0

किसी ने इस तरह की एक प्रश्न पूछा लगभग ठीक ... http://stackoverflow.com/questions/10055631/how- do-i-insert-spaces-in-a-string-use-the-range-function/10055656 # 10055656 – jamylak

+0

संभावित डुप्लिकेट: http://stackoverflow.com/questions/10055631/how-do-i-insert-spaces -into एक स्ट्रिंग का उपयोग-वें ई-रेंज-फ़ंक्शन –

+0

यह भी थोड़े समान है: http://stackoverflow.com/questions/10061008/generating-all-n-tuples-from-a-string/10061368 – jamylak

उत्तर

11
def encrypt(string, length): 
    return ' '.join(string[i:i+length] for i in xrange(0,len(string),length)) 

encrypt('thisisarandomsentence',4)

'this isar ando msen tenc e' 
+0

आईटी काम किया !!! तुम कमाल हो! धन्यवाद – user15697

+0

पायथन 3 के साथ संगत होने के लिए श्रेणी –

1

itertools grouper recipe का उपयोग करने देता है:

>>> from itertools import izip_longest 
>>> def grouper(n, iterable, fillvalue=None): 
     "Collect data into fixed-length chunks or blocks" 
     # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx 
     args = [iter(iterable)] * n 
     return izip_longest(fillvalue=fillvalue, *args) 

>>> text = 'thisisarandomsentence' 
>>> block = 4 
>>> ' '.join(''.join(g) for g in grouper(block, text, '')) 
'this isar ando msen tenc e' 
+1

द्वारा xrange को प्रतिस्थापित करें :) भी काम किया !! पिछले 6 घंटों के लिए यह खोज रहा है !! – user15697

संबंधित मुद्दे