WorldViz User Forum

WorldViz User Forum (https://forum.worldviz.com/index.php)
-   Vizard (https://forum.worldviz.com/forumdisplay.php?f=17)
-   -   String within a string problem? (https://forum.worldviz.com/showthread.php?t=1626)

Elittdogg 08-29-2008 08:40 AM

String within a string problem?
 
I'm sure this is very basic, but for whatever reason I'm unable to wrap my head around it. I'm using python based code only.

Code:

x=raw_input("Enter something for x or enter 'quit' to exit the program: ")
y=raw_input("Enter a choice (#, a, or b): ")

if x == 'quit':
    print 'Done.  Thank you.'
else:
    print y

if y.isdigit():
    print x[y]

and this is what happens:
Enter something for x or enter 'quit' to exit the program: hello
Enter a choice (#, a, or b): 2
2

Traceback (most recent call last):
File "C:/Python25/homework 1 Littman.py", line 10, in
print x[y]
TypeError: string indices must be integers


What should come up is l. I need to be able to specify which place in the string the number corresponds to. For instance, (and this works) if I set x='monkey' and y=2. Then I print x[y] I get n. Why doesn't it work when I enter in 2 into the prompt???

So my 3 choices are a number, a or b. If it's a number then I need to output the correct letter from the string (but of course it can't exceed the length of the string). If I enter a, I need to output the length of the string (so hello would be 5 (I also need to start counting from 1, not 0). And if I enter b I need to output the initial string in all CAPS (so I'd need hello to be HELLO). Right now I can't get past the integer and I don't know why.

farshizzo 08-29-2008 01:35 PM

The raw_input function returns a string object, which cannot be used as an index in a list. You will need to convert the string to an integer first:
Code:

index = int(y)
print x[index]



All times are GMT -7. The time now is 05:15 AM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Copyright 2002-2023 WorldViz LLC