私は次のコードを持っている:Pythonの文字列を保存する際にエラーが発生しましたか?
print(title)
f = io.open("1.txt", "a", encoding="utf-8")
f.write(title + '\n')
f.close()
を私はエラーを取得:私が使用
TypeError('can only concatenate list (not "str") to list',))
をPythonの3.5
私は次のコードを持っている:Pythonの文字列を保存する際にエラーが発生しましたか?
print(title)
f = io.open("1.txt", "a", encoding="utf-8")
f.write(title + '\n')
f.close()
を私はエラーを取得:私が使用
TypeError('can only concatenate list (not "str") to list',))
をPythonの3.5
ジョイン機能を使用して文字列をリストに変換することができます:
" ".join(["This", "is", "a", "list", "of", "strings"])
>>> This is a list of strings
私たちは通常、「with-syntax」を使ってファイルを書き込み/読み込みします:
with open('workfile.txt', 'w') as f:
f.write("My entry line\n")
f.write(" ".join(["Other", "line", "here"]))
f.write("\n")
title
は文字列型の変数ですか?あなたは、文字列、このために、変数の型をチェックすることができます
str(title)
:あなたが書き込むことで文字列にtitle
をキャストすることができ、省
import io
title = "My Title"
print(title)
f = io.open("1.txt", "a", encoding="utf-8")
f.write(title + '\n')
f.close()
がために:
あなたのコードは、この例ではエラーなしで実行されますway:
if type(title) is str:
print("It's a string")
入力があった場合は、 Jeanderson BarrosCândidoが提案した解決策。
私は 'type(title)'を実行し、 '
を得ました。 'title'を値に設定した行を表示できますか? 質問のエラーメッセージがスクリプトの別の行を参照している可能性はありますか? –
もう少し文脈を与えることができますか?変数 'title'とは何ですか?そして、どの行でエラーが発生していますか? –
'title'は' Mortal Combat'の文字列です – Griboedov
'title'はリストであり、文字列ではありません。問題の中で 'title''が値を持つ行を提供する必要があります。そうすれば、何が間違っているのか、それを解決する方法がわかります。 –