python_examples/rand_char.py

48 lines
1.2 KiB
Python
Raw Normal View History

2023-08-23 12:02:52 -04:00
#!/usr/bin/env python3
"""
Generate and Print Random Unicode Characters
This module generates a string of random Unicode characters, specifically avoiding the
surrogate pair range (0xD800 to 0xDFFF). The generated string has a default length of
5000 characters.
Usage:
Run the script with an argument to specify the length of the string to be generated:
`python script_name.py 5000`
"""
2023-08-23 11:11:51 -04:00
import random
2023-08-23 12:02:52 -04:00
from argparse import ArgumentParser
def generate_string(length):
characters = ""
try:
characters = "".join(
[
chr(
random.choice(
[i for i in range(0x0, 0xD7FF + 1) if i < 0xD800 or i > 0xDFFF]
)
)
for _ in range(length)
]
)
except UnicodeEncodeError as e:
print(f"Error encoding character: {e}")
return(characters)
2023-08-23 11:11:51 -04:00
2023-08-23 12:02:52 -04:00
if __name__ == "__main__":
parser = ArgumentParser(
description="Generate a string of random Unicode characters."
)
parser.add_argument(
"length",
type=int,
default=5000,
help="Length of the string to be generated.",
)
args = parser.parse_args()
2023-08-23 11:11:51 -04:00
2023-08-23 12:02:52 -04:00
print(generate_string(args.length))