开发者

Python random digit letter and additional generator

I would like to generate a random number string of N length with this code:

import random
import string

N=512
print ''.join(random.choice(开发者_开发技巧string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(N))

What is missing is that I would like to add "special characters like e.g. "@,;:.§$%&/(!"" And I would like to output that to .txt file with a newline after for a example 10,15 signs.

Any help would be great.

Thanks for the time.


string module has a class for such special characters:

>>> print string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

To save generated string to file use something like:

N=512
chars_per_line = 15

s = ''.join(random.choice(string.digits + string.ascii_letters + string.punctuation) for i in xrange(N))

fh = open('filename', 'w')
try:
    fh.writelines([s[i:i+chars_per_line]
                   for i in range(0, N, chars_per_line)])
finally:
    fh.close()


import random
import string

allowable_gibberish = string.ascii_letters + string.digits + string.punctuation
def gibberish_maker(gibberish=allowable_gibberish,n=512,new_line_every=15):
    str = ''.join(random.choice(gibberish) for x in range(n))
    return '\n'.join(str[i:i+new_line_every] for i in xrange(0, len(str), new_line_every))

Note: string.ascii_letters is the same as string.ascii_uppercase + string.ascii_lowercase.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜