【问题标题】:Python: Does not Increment Integer Value inside of StringPython:不增加字符串内的整数值
【发布时间】:2020-04-05 20:01:06
【问题描述】:

我对 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_0public 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;
    }
}

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

非常感谢

【问题讨论】:

    标签: python python-3.x for-loop increment


    【解决方案1】:

    那是因为您在 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)
    

    【讨论】:

    • 感谢您的回答。我已经尝试过你的代码,它完美地工作了我想要的。非常感谢
    猜你喜欢
    • 2012-04-09
    • 2017-05-28
    • 2021-07-17
    • 2012-11-06
    • 1970-01-01
    • 2013-05-12
    • 2018-11-28
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多