python-根据输入的模板输出对应字符串

import random
import string
dict_num='0123456789'
dict_num_letter='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
dict_num_letter_all='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
dict_symbol='!@#$%^&*()-_+={[}]\\|":;?/>.<,~'

def random_seq(choice_seq,count=3,repeatable=True):
    if repeatable:
        return [random.choice(choice_seq) for _ in range(count)]
    return random.sample(choice_seq,count)
def num_shuffle(count,repeatable=True):
    digits=random_seq(string.digits,count,repeatable=True)
    random.shuffle(digits)
    return ''.join(digits)
def uppercase_shuffle(count,repeatable=True):
    letters=random_seq(string.ascii_uppercase,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def lowercase_shuffle(count,repeatable=True):
    letters=random_seq(string.ascii_lowercase,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def letter_shuffle(count,repeatable=True):
    letters=random_seq(string.ascii_letters,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def num_letter_shuffle(count,repeatable=True):
    letters=random_seq(dict_num_letter,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def num_letter_all_shuffle(count,repeatable=True):
    letters=random_seq(dict_num_letter_all,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def symbol_shuffle(count,repeatable=True):
    letters=random_seq(dict_symbol,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)

def generate_template_words(dict_template):
    '''
    u代表大写字母A-Z
    l代表小写字母a-z 
    n代表数字0-9
    a代表大小写字母A-Z a-z的混合
    b代表大写字母A-Z与数字0-9的混合
    c代表大小写字母A-Z a-z与数字0-9的混合
    s代表通用特殊符号:!@#$%^&*()-_+={[}]\\|":;?/>.<,~ 
    '''
    str_list={'u':uppercase_shuffle,'l':lowercase_shuffle,'n':num_shuffle,'a':letter_shuffle,'b':num_letter_shuffle,'c':num_letter_all_shuffle,'s':symbol_shuffle}
    str=''
    start_word=''
    count=1
    par_if=False
    for index in range(len(dict_template)):
        if dict_template[index] in str_list.keys() and par_if==False:
            if start_word!='' and dict_template[index]==start_word:
                count+=1
                if index==len(dict_template)-1:
                    str+=str_list[start_word](count)
            else:
                if start_word!='':
                    str+=str_list[start_word](count)
                    count=1
                    start_word=dict_template[index]
                else:
                    start_word=dict_template[index]
        else:
            if dict_template[index]=='{':
                par_if=True
                if start_word!='':
                    str+=str_list[start_word](count)
                    count=1
            if dict_template[index]!='{' and par_if:
                if dict_template[index]=='}':
                    par_if=False
                    start_word=''
                else:
                    str+=dict_template[index]
        
    print(str)
    return str

if __name__=='__main__':
    generate_template_words('nnn{-}{JK}nnn') #随机生成 720-JK055 551-JK156 等等

更高级玩法:

import random
from random import randint
import string
dict_num='0123456789'
dict_num_letter='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
dict_num_letter_all='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
dict_symbol='!@#$%^&*()-_+={[}]\\|":;?/>.<,~'

def random_seq(choice_seq,count=3,repeatable=True):
    if repeatable:
        return [random.choice(choice_seq) for _ in range(count)]
    return random.sample(choice_seq,count)
def num_shuffle(count,repeatable=True):
    digits=random_seq(string.digits,count,repeatable=True)
    random.shuffle(digits)
    return ''.join(digits)
def uppercase_shuffle(count,repeatable=True):
    letters=random_seq(string.ascii_uppercase,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def lowercase_shuffle(count,repeatable=True):
    letters=random_seq(string.ascii_lowercase,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def letter_shuffle(count,repeatable=True):
    letters=random_seq(string.ascii_letters,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def num_letter_shuffle(count,repeatable=True):
    letters=random_seq(dict_num_letter,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def num_letter_all_shuffle(count,repeatable=True):
    letters=random_seq(dict_num_letter_all,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
def symbol_shuffle(count,repeatable=True):
    letters=random_seq(dict_symbol,count,repeatable=True)
    random.shuffle(letters)
    return ''.join(letters)
    
def generate_template_words(dict_template):
        '''
        u代表大写字母A-Z
        l代表小写字母a-z 
        n代表数字0-9
        a代表大小写字母A-Z a-z的混合
        b代表大写字母A-Z与数字0-9的混合
        c代表大小写字母A-Z a-z与数字0-9的混合
        s代表通用特殊符号:!@#$%^&*()-_+={[}]\\|":;?/>.<,~ 
        如果固定哪些字符用英文{}括起来(包含空格),如果固定选择哪些字符用英文()括起来,英文逗号隔开
        例如:332-JK123 如果中间横杠-是固定的,其他字母随机则:nnn{-}uunnn 
                        如果JK字母也是固定的,则:nnn{-}{JK}nnn 
                        如果首个数字是固定在3,6,8中选择的,则:{(3,6,8)}nn{-}{JK}nnn
        '''
        str_list={'u':uppercase_shuffle,'l':lowercase_shuffle,'n':num_shuffle,'a':letter_shuffle,'b':num_letter_shuffle,'c':num_letter_all_shuffle,'s':symbol_shuffle}
        str=''
        start_word=''
        count=1
        par_if=False
        index=0
        while index<(len(dict_template)):
            if dict_template[index] in str_list.keys() and par_if==False:
                if start_word!='' and dict_template[index]==start_word:
                    count+=1
                    if index==len(dict_template)-1:
                        str+=str_list[start_word](count)
                else:
                    if start_word!='':
                        str+=str_list[start_word](count)
                        count=1
                        start_word=dict_template[index]
                    else:
                        start_word=dict_template[index]
            else:
                if dict_template[index]=='{':
                    par_if=True
                    if start_word!='':
                        str+=str_list[start_word](count)
                        count=1
                if dict_template[index]!='{' and par_if:
                    if dict_template[index]=='}':
                        par_if=False
                        start_word=''
                    elif dict_template[index]=='(':
                        str_0=dict_template[index+1:].split(')')[0].split(',')
                        str+=random.choice(str_0)
                        index+=(len(str_0)+len(str_0)-1+1)
                        par_if=False
                        if index+2<len(dict_template):
                            #start_word=dict_template[index+2]
                            count=1
                    else:
                        str+=dict_template[index]
            index+=1
        print(str)
        return str
    
if __name__ == '__main__':
    generate_template_words(dict_template='{(3,6,8)}nn{-}{JK}nnn') #307-JK676 346-JK533 691-JK491等等

 

### Python 字符串格式化输出方法 Python 提供了多种字符串格式化的方式,每种方式都有其特点和适用场景。以下是几种常见的字符串格式化方法及其示例: #### 1. `%` 格式化字符 这是最早的一种字符串格式化方法,在 Python 的早期版本中被广泛使用。通过 `%` 符号可以将变量插入到字符串中的指定位置。 ```python name = "Alice" age = 30 formatted_str = "My name is %s and I am %d years old." % (name, age) print(formatted_str) # 输出: My name is Alice and I am 30 years old. ``` 这种方法简单直观,但在复杂情况下可能会显得不够灵活[^3]。 --- #### 2. `str.format()` 方法 `str.format()` 是一种更为现代的字符串格式化方法,自 Python 2.7 起引入。它允许开发者通过 `{}` 占位符定义模板,并在 `.format()` 方法中传入对应的参数。 基本用法如下: ```python name = "Alice" age = 30 formatted_str = "My name is {} and I am {} years old.".format(name, age) print(formatted_str) # 输出: My name is Alice and I am 30 years old. ``` 还可以通过索引或关键字命名占位符来增强可读性和灵活性: ```python formatted_str_with_index = "{1} is {0} years old.".format(age, name) print(formatted_str_with_index) # 输出: Alice is 30 years old. formatted_str_with_keywords = "Name: {n}, Age: {a}".format(n=name, a=age) print(formatted_str_with_keywords) # 输出: Name: Alice, Age: 30 ``` 这种方式相较于 `%` 更加清晰易懂,适合处理复杂的格式需求[^1]。 --- #### 3. F-string(格式化字符串字面量) F-string 自 Python 3.6 开始引入,是一种简洁高效的字符串格式化工具。它可以将表达式嵌入到字符串中,语法更加直观。 ```python name = "Alice" age = 30 formatted_str = f"My name is {name} and I am {age} years old." print(formatted_str) # 输出: My name is Alice and I am 30 years old. ``` 除了简单的变量替换外,F-string 还支持直接嵌套表达式: ```python price = 49.95 tax_rate = 0.08 total_price = price * (1 + tax_rate) receipt = f"Price: ${price:.2f}\nTax Rate: {tax_rate*100}%\nTotal Price: ${total_price:.2f}" print(receipt) # 输出: # Price: $49.95 # Tax Rate: 8% # Total Price: $53.95 ``` 由于其高效性和易读性,F-string 已成为当前推荐的主要字符串格式化方法[^2]。 --- #### 4. 整数填充与对齐 对于一些特定场合下的格式化需求,比如固定宽度的整数输出或者小数转百分比,也可以利用这些方法完成。 ##### 小数转百分比 ```python percentage = 0.75 formatted_percentage = "%.2f%%" % (percentage * 100) print(formatted_percentage) # 输出: 75.00% # 使用 F-string 实现相同效果 formatted_fstring = f"{percentage * 100:.2f}%" print(formatted_fstring) # 输出: 75.00% ``` ##### 数字补零 ```python for i in range(1, 20): padded_number = "%03d" % i print(padded_number) # 使用 zfill() 方法实现同样功能 padded_number_zfill = str(i).zfill(3) print(padded_number_zfill) ``` --- ### 总结 以上介绍了 Python 中常用的三种字符串格式化方法:`%` 格式化字符、`str.format()` 和 F-string。其中,F-string 因为其简洁性和性能优势逐渐取代其他两种方法,特别是在新项目开发中应优先考虑使用 F-string[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值