-1
line0 = "hello"
line1 = "stack"
line2 = "overflow"
linenum = 1
for x in range(3):
    linenum = "line%d"%(x)
    print(linenum)

I would like to print hello stack overflow but it just prints: line0 line1 line2

5 Answers5

1

You are constructing variable names dynamically. You can get the global namespace dictionary and look them up from there.

line0 = "hello"
line1 = "stack"
line2 = "overflow"
linenum = 1
for x in range(3):
    linenum = globals()["line%d"%(x)]
    print(linenum)

Its common to use a list or dictionary to hold data you want to lookup by way of an index or name. For instance,

lines = ["hello", "stack", "overflow"]

Whether that's the best thing in this case is a design decision for you.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • This Worked: line0 = "hello" line1 = "stack" line2 = "overflow" lines = [line0, line1, line2] ans = "" for x in range(len(lines)): ans += lines[x] print(ans) Credit to @FoundABetterName – MrKeviscool Aug 24 '22 at 04:55
  • 1
    This works, and it's probably the most precise answer to the question. But plucking things out of the global namespace is not usually the best solution. I hope OP will think a bit more and come up with a solution the the actual problem being faced that doesn't do this. – Z4-tier Aug 24 '22 at 04:56
  • @MrKeviscool - Right, that is much like my example of `lines = ["hello", "stack", "overflow"]` except that it also binds the values to variables `line0`, `line1` and `line2`. If you don't need those variable names in your program, then you wouldn't do that extra step. In the short example given, its not necessary. – tdelaney Aug 24 '22 at 05:01
0

This worked:

line0 = "hello"
line1 = "stack"
line2 = "overflow"
lines = [line0, line1, line2]
ans = ""
for x in range(len(lines)):
    ans += lines[x]
print(ans)
0

Below is the solution. I have used the list here. Hope it helps.

lines_list = ["hello", "stack", "overflow"]
for i in range(0, len(lines_list)):
    print (lines_list[i]),
Aman Raheja
  • 615
  • 7
  • 16
0
line0 = "hello "
line1 = "stack "
line2 = "overflow "
linenum = line0 + line1 +line2
for x in range(1):
    print(linenum)

Output: hello stack overflow.

Here is one way to print hello stack overflow. Hope this helps.

-1

Use list is best practice.

lines=['hello','stack','overflow']
print(*lines, sep=' ')

If you don't want use list then try this.

line0 = "hello"
line1 = "stack"
line2 = "overflow"
for x in range(3):
    exec(f'print(line{x},end=" ")')
dhkim
  • 81
  • 5