Home > Blockchain >  How do i get my output to not come out as (1, '.txt')
How do i get my output to not come out as (1, '.txt')

Time:02-05

I was trying to create copies of a txt document a couple of times to automate some of my tasks. So I created a loop that adds 1 to a variable every time it runs. When I added this to my main code it came back with the weird output of (1, '.txt'). Is there a way that I can just get it to say 1.txt, 2.txt, 3.txt, ect. I thought it was an issue with the number not being a string but I don't think that is the issue. Any help would be greatly appreciated!

num = 1
while num < 10:
    #print(num)
    num  = 1
    numtxt = num
    txttxt = ".txt"
    maintxt = numtxt, txttxt
    #maintxtsrt = str(maintxt)
    print(maintxt)
    #print(maintxtsrt)

CodePudding user response:

Try

maintext = str(numtxt) txttxt

CodePudding user response:

With this line:

maintxt = numtxt, txttxt

you create a tuple. The whole code can be just:

for num in range(1, 10):
    print(f'{num}.txt')

CodePudding user response:

That is because you made a tuple by maintxt = numtxt, txttxt.

Instead, I changed a type of numtxt to str and concat with txttxt to make correct filename.

num = 1
while num < 10:
    #print(num)
    num  = 1
    numtxt = num
    txttxt = ".txt"
    maintxt = str(numtxt)   txttxt # fixed
    print(maintxt)

CodePudding user response:

If maintxt is already an (int, str) tuple, you could convert it into a single joined string with join and map:

    numtxt = num
    txttxt = ".txt"
    maintxt = numtxt, txttxt
    print(''.join(map(str, maintxt)))

But it's simpler to just create maintxt as a string:

    maintxt = f"{num}.txt"  # creates a single string like "1.txt"

You can also simplify your num loop by using for and range instead of a while and a manually incrementing variable:

# prints "1.txt", "2.txt", ..., "9.txt"
for num in range(1, 10):
    print(f"{num}.txt")

CodePudding user response:

possible solutions:

  1. it is better if you start your num with zero, so when you increment inside your while it will start from 1
  2. str(num) will change integer to string
  3. you get tuple because of this line maintxt = numtxt, txttxt

this code will give you the result that you want num = 0

while num < 10:

num  = 1

numtxt = str(num)
txttxt = ".txt"
maintxt = numtxt   txttxt
print(maintxt)`
  •  Tags:  
  • Related