2016-11-06 4 views
-2
Traceback (most recent call last): 
    File "<pyshell#0>", line 1, in <module> 
    get_odd_palindrome_at('racecar', 3) 
    File "C:\Users\musar\Documents\University\Courses\Python\Assignment 2\palindromes.py", line 48, in get_odd_palindrome_at 
    for i in range(string[index:]): 
TypeError: 'str' object cannot be interpreted as an integer 

整数として解釈することはできません私は値インデックスを使用するにはを参照するが、私はそれをどのように行うのですか?(ヘルプ)はTypeError:「strの」オブジェクトが

+0

この問題の原因は何でしょうか?これまでに何を試しましたか?あなたは何を探しましたか? http://stackoverflow.com/help/how-to-ask – RJHunter

+0

あなたのコードを投稿してください –

答えて

1

'index'変数は文字列ではなくintであると思われます。 int()を使用して変換できます。

index = int(index) 
for i in range(string[index:]): 

ここで、文字列[index:]も文字列になります。だからあなたもそれを変換する必要があります:

>>> string = "5" 
>>> range(string) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: range() integer end argument expected, got str. 
>>> range(int(string)) 
[0, 1, 2, 3, 4] 
>>> 

これは、文字列[インデックス:]には数字だけが含まれていると仮定しています。 the Wikipedia article on Pythonから

# 'index' contains only numbers 
index = int(index) 
number = string[index:] 
if number.isdigit(): 
    number = int(number) 
    for i in range(number): 

:それは必ずしもそうではない場合、あなたが何かを行うことができます。この場合

Python uses duck typing and has typed objects but untyped variable names. Type constraints are not checked at compile time; rather, operations on an object may fail, signifying that the given object is not of a suitable type. Despite being dynamically typed, Python is strongly typed, forbidding operations that are not well-defined (for example, adding a number to a string) rather than silently attempting to make sense of them.

を、あなたは)(レンジに文字列を渡すためにしてみてください。この関数は数値(正の整数)を待ちます。そのため、文字列をintに変換する必要があります。あなたは実際にあなたのニーズに応じて、もう少しチェックをすることができます。 Pythonは型を気にします。

HTH、

+0

インデックスは実際には私の関数のパラメータであり、文字列のインデックス値を参照するintを参照します。パラメータの値をインデックスとして使用したいのですが、どうすればいいですか? def get_odd_palindrome_at(string、index): '' '(str、int) - > str 指定されたインデックスを中心とする文字列の最長奇数長回文を返します。 –

+0

引用符で囲まれた例外(文字列[index:]): TypeError: 'str'オブジェクトは整数として解釈できません)、 'インデックス'には実際には文字列が含まれています。 。関数に整数を渡すことを確認する必要があります。文字列はPython(そしてほとんどの言語で)の数値を含むことができます。var = "3"は整数ではなく文字列を作成します。申し訳ありませんが、それは明白な音が、時には忘れてしまった。 –

+0

また、短い答えでは、関数の最初の行でインデックスを変換することができます:index = int(index)。しかし、関数に送信するデータのタイプをチェックする方がはるかに優れています。関数が文字列とintを必要とする場合は、文字列とintを送信する必要があります。 –

関連する問題