首页 > 解决方案 > Python:不增加字符串内的整数值

问题描述

我对 Python 编码有疑问,我使用的 IDE 是 Pycharm 社区版。

我有这样的代码

i = 0
str_1 = """public class Schedule_Boolean_Monday_""" + str(i) + """ {

public Schedule_Boolean_Monday_""" + str(i) + """_3(Context context){
    this.mContext = context;
    }
}"""

for i in range(3):
     print(str_1)

电流输出是这样的

public class Schedule_Boolean_Monday_0 {

public Schedule_Boolean_Monday_0_3(Context context){
    this.mContext = context;
    }
}
public class Schedule_Boolean_Monday_0 {

public Schedule_Boolean_Monday_0_3(Context context){
    this.mContext = context;
    }
}
public class Schedule_Boolean_Monday_0 {

public Schedule_Boolean_Monday_0_3(Context context){
    this.mContext = context;
    }
}

public class Schedule_Boolean_Monday_0并且public Schedule_Boolean_Monday_0_3(Context context)不要改变。String 中的 str(i) 不会增加。

我想得到这样的输出

public class Schedule_Boolean_Monday_0 {

public Schedule_Boolean_Monday_0_3(Context context){
    this.mContext = context;
    }
}
public class Schedule_Boolean_Monday_1 {

public Schedule_Boolean_Monday_1_3(Context context){
    this.mContext = context;
    }
}
public class Schedule_Boolean_Monday_2 {

public Schedule_Boolean_Monday_2_3(Context context){
    this.mContext = context;
    }
}

这是否可以在字符串内增加整数值?我很想听听你的建议。

非常感谢

标签: pythonpython-3.xfor-loopincrement

解决方案


那是因为您在i为 0 时分配它。它不会在循环内更新。尝试将字符串赋值放在循环中

for i in range(3):
    str_1 = f"""public class Schedule_Boolean_Monday_""" + str(i) + """ {

    public Schedule_Boolean_Monday_""" + str(i) + """_3(Context context){
        this.mContext = context;
        }
    }"""
    print(str_1)

推荐阅读