Home > database >  How to append string in the middle of a pre-existing csv line?
How to append string in the middle of a pre-existing csv line?

Time:11-16

I am fairly new to working with python and finally encountered a problem I cannot circumvent. I will make this fairly simple.

I have a csv file with many lines that looks like this once I create a list variable:

['1\t10000\t11000\tabcdef\t1\t \t10000\t11000\t"0,0,0"\t1\t1000\t0\n']

I want to add 2 new string variables after the final \t0 before the \n. Its important to indicate I still want the \t before str1 and str2. So the output I desire should look like this:

['1\t10000\t11000\tabcdef\t1\t \t10000\t11000\t"0,0,0"\t1\t1000\t0\tstr1\tstr2n']

Thanks for your help!

str1 = hello
str2 = world
line = ['1\t10000\t11000\tabcdef\t1\t \t10000\t11000\t"0,0,0"\t1\t1000\t0\n']
line.append(('\t')   str1   ('\t')   str2)
print(line)

Current output:

['1\t10000\t11000\tabcdef\t1\t \t10000\t11000\t"0,0,0"\t1\t1000\t0\n', '\tstr1\tstr2']

CodePudding user response:

The append method adds the input to the list you use it on. Since line is a list, you are getting a new entry into your list.

If you want to keep your string inside the list, you need to access the 0th index of the list to change the string:

line[0]

Once you have the string you need to separate it into two and add your new strings:

line[0] = line[0][:-2]   newinput   line[0][-2:]

Note the -2 separated because you want to separate the last two characters of your string: \n

CodePudding user response:

append() is for adding an element to a list. To add to a string, use = on the variable that contains the string, which is line[0].

line[0]  = f'\t{str1}\t{str2}'

That said, it's strange that you have the entire line as a single element of the list, rather than parsing the CSV row into a list of fields, using \t as the field delimiter.

  • Related