-2

I want to name a variable in python using the name of an existing variable. For example:

s = "Hello World"
words = s.split()
numofwords = len(words)
word(numofwords) = words[numofwords-1]

I'm not sure what syntax I would use to define the variable in line 4. What my code would hopefully do is print the last word in the string, stored as the variable wordx, x being the number of the last word. (In this case it would be 2.)I'm new to Python so there are probably some mistakes in the code.

Theo
  • 1
  • 1
  • 1
    This can be of help: https://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name – Naman Doctor Oct 17 '20 at 10:47
  • 1
    There definitely are a number of mistakes in the code but my suggestion to you is to really stop this train of thought before it goes further. Herein lies pain – roganjosh Oct 17 '20 at 10:47
  • Note that ``words`` already provides what you desire – it has a well-known name and provides access to individual items. You merely write ``words[1]`` instead of ``words2``. – MisterMiyagi Oct 17 '20 at 10:53

2 Answers2

0

You can use dictionery:

s = "Hello World"
words = s.split()
numofwords = len(words)
varname = "word" + str(numofwords)
vars = dict()
vars[varname] = words[numofwords-1]

and then you can access it like this:

print(vars[varname])
Yuval.R
  • 1,182
  • 4
  • 15
0

Use a dictionary instead:

s = "Hello World"
words = s.split()
numofwords = len(words)
myVar = "word"+str(numofwords)
myVars = {}
myVars[myVar] = words[numofwords-1]

And get it using:

myVars[myVar]

To print:

print(myVars[myVar])
Wasif
  • 14,755
  • 3
  • 14
  • 34