String sub-stituir per variable

Asked

Viewed 48 times

0

i have the following text inside a.txt file

[ExpertSingle]
{
    1050 = N X 0
    1260 = N X 0
    1470 = N X 0
    1680 = N X 0
    1890 = N X 0
    2100 = N X 0

I want to turn "X" into numbers using Choice Ring to look like this

[ExpertSingle]
{
    1050 = N 2 0
    1260 = N 0 0
    1470 = N 4 0
    1680 = N 0 0
    1890 = N 1 0
    2100 = N 3 0

I made this code "copied from several videos I watched"

import random
import fileinput

file_name = 'C:/Users/Felipe/Desktop/GH.txt'

c3 = (random.choice([0, 1, 2, 3, 4]))

for line in fileinput.FileInput(file_name,inplace=1):
    if 'X' in line:
        line = line.rstrip()
        line = line.replace('X','c3',1)
    print (line)

I got this result kkk

[ExpertSingle]

{

    1050 = N c3 0
    1260 = N c3 0
    1470 = N c3 0
    1680 = N c3 0
    1890 = N c3 0
    2100 = N c3 0

I don’t know where I went wrong and I don’t know how to get the desired result can anyone help me please?

  • Instead of using C3 as a string, it would not be the case to put `line = line.replace('X',str(Random.Choice([0, 1, 2, 3, 4])),1)

2 answers

1

In this line

line = line.replace('X','c3',1)

You are replacing 'X' for string 'c3', not at variable value c3 as you wish. To access the value of a variable you should not use quotes.

You probably added the quotes because when you tried without getting the error:

TypeError: replace() argument 2 must be str, not int

And this happened because the value of c3 is a whole, but to replace in a string he also needs to be a string. For that, do str(c3). In addition, you are only drawing a random value and using it on all lines; from what you described in the question it seems that you want each line to have a different random value, so you will need to do the draw within the loop.

  • Omg worked really thank you, I just didn’t understand how to do this draw inside the repeat gap, how I apply that in the code?

  • @Like you did, only instead of leaving c3 = random.choice(...) out of the loop for you will need to put it in so that at each generated iteration drawn a new value.

  • You’re right everything you said, thank you very much

0

so was the code after the help of friends

import random
import fileinput

file_name = 'C:/Users/Felipe/Desktop/CHART.txt'


for line in fileinput.FileInput(file_name,inplace=1):
    c3 = (random.choice([0, 1, 0, 1]))
    if 'X' in line:
        line = line.rstrip()
        line = line.replace('X', str(c3),1)
    print (line)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.