Python在循环中增加参数数量

huangapple go评论73阅读模式
英文:

Python increase parameter number in loop

问题

我现在也想遍历“TEXT_1”,因为还有“TEXT_2”,“TEXT_3”等,它们都应该从dataframe1.iloc[1,1+i]获取不同的值。但我不知道如何遍历TEXT_n。你能帮助我吗?

非常感谢,

Jerry

英文:

I have a text file where I want to replace some placeholder strings with data from an Excel file. Therefore I created this code:

import pandas as pd

with open('testfile_1.txt', 'r') as file :
  filedata = file.read()

dataframe1 = pd.read_excel('EXCEL_Data.xlsx', header=None)

values = range(5)
for i in values:
    filedata = filedata.replace('TEXT_1', dataframe1.iloc[1,1+i])

I now also want to iterate through "TEXT_1" since there is "TEXT_2", "TEXT_3", etc. which should all get different values from dataframe1.iloc[1,1+i]

But I don`t know how to iterate through TEXT_n. Can you please help me?

Thank you very much,

Jerry

答案1

得分: 0

如果你需要 'TEXT_i',你可以使用字符串拼接:'TEXT_' + str(i + 1)。另一种方法是使用字符串插值:f'TEXT_{i + 1}'。这两种方法都会给你 'TEXT_1'、'TEXT_2'、...、'TEXT_5'。

英文:

If you need 'TEXT_i', you can use string concatenation: 'TEXT_' + str(i + 1). Other way is to use string interpolation: f'TEXT_{i + 1}'. Both methods will give you 'TEXT_1', 'TEXT_2', ..., 'TEXT_5'.

huangapple
  • 本文由 发表于 2023年5月6日 16:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定