edubun
日本語

文字列:文字を扱う

Pythonは"Python"の文字を0から数えるので、"Python"[5]は最後の文字n、"Python"[6]はエラーです。

名札のテキストを複数の部分から組み立てる

学校の行事やクラブの集まりの名札を考えてみましょう。どの札も同じレイアウトで、名前だけが違うので、プログラムは1つのパターンからすべてを印刷できます。Pythonでテキストを表すのは文字列(str)で、部品から文字列を組み立てる最も手早い方法がf文字列です。開き引用符の前に文字fを置き、波括弧の中に変数名を書きます。Pythonは各{name}を、その変数の値に置き換えます。

name = "Mina"
club = "Robotics"
print(f"Hello, {name}!")
print(f"{name} joined {club}.")
出力
Hello, Mina!
Mina joined Robotics.

文字をつなぐ古い方法が2つあります。+演算子は文字列を端から端へつなぎ、*は文字列をくり返します。+の両辺は文字列でなければならないので、数は先にstr()で文字に変える必要があります。f文字列はその変換を代わりにしてくれるので、ふつうに選ばれる理由の1つです。

item = "gimbap"
count = 2
print(item + " x " + str(count))
print("-" * 12)
print(f"{item} x {count}")
出力
gimbap x 2
------------
gimbap x 2

各文字には位置の番号があり、0から始まる

文字列は文字の並びで、各文字にインデックスがあります。最初の文字は1ではなく、インデックス0にあります。角括弧で1文字を選びます。word[0]が最初です。負のインデックスは末尾から数えるので、word[-1]は、長さに関係なく、いつも最後の文字です。len()は、空白と句読点を含む文字数を返します。

"Python"のインデックス番号:前から0〜5、後ろから-6〜-1。スライスword[0:2]はインデックス2の前で止まります。
word = "Python"
print(word[0], word[5], word[-1])
print(len(word))
print(word[0:2], word[2:])
出力
P n n
6
Py thon

word[0:2]はスライスです。インデックス0から始まり、インデックス2の直前で止まって、"Py"を返します。word[2:]のように終わりを省くと、スライスは文字列の最後まで続きます。「手前で止まる」規則は最初は変に見えますが、そのおかげでword[0:2] + word[2:]はいつも単語全体を返します。

文字列のメソッドは新しい文字列を返す

文字列には、ドットの後ろに書く、メソッドという組み込みの道具があります。upper()とlower()は大文字小文字を変え、replace(old, new)は指定した部分文字列の出現箇所をすべて別の文字列に置き換え、strip()は両端の空白を取り除きます。フォームに誰かが余分な空白を入力したときに役立ちます。キーワードinは、ある文字列が別の文字列の中に現れるかを調べ、TrueかFalseを返します。これらはどれも元の文字列を変えません。文字列は作られたあとで変更できません。各メソッドは新しい文字列を返し、それを名前に代入して取っておきます。

menu = "  tteokbokki  "
clean = menu.strip()
print(clean.upper())
print(clean.replace("k", "K"))
print("bok" in clean, len(menu), len(clean))
出力
TTEOKBOKKI
tteoKboKKi
True 14 10

文字列の中に引用符を入れるには、その外側に別の種類の引用符を使います:"It's fine"。バックスラッシュはエスケープシーケンスを始めます。文字列の中の\nは「ここで改行」を意味するので、1つのprintで2行を表示できます。

print("It's lunch time.")
print("Line one\nLine two")
出力
It's lunch time.
Line one
Line two
f文字列f"...{name}..."は、値を文字の中に入れる
インデックス文字の位置の番号。0から始まる
スライスs[a:b]:インデックスaから、bは含まずにbの手前まで
len()文字列の文字数
メソッドs.upper()のように、ドットの後ろに書く道具
\n改行のエスケープシーケンス
in"a" in "cat"はTrueを返す
  1. このコードは何を出力しますか。
    word = "banana"
    print(word[1])
  2. このコードは何を出力しますか。
    word = "banana"
    print(word[-2])
  3. このコードは何を出力しますか。
    print(len("Hi there!"))
  4. このコードは何を出力しますか。
    word = "school"
    print(word[1:4])
  5. このコードは何を出力しますか。
    name = "Jun"
    print(f"Hi {name}, you are {13 + 1}.")
  6. このコードは何を出力しますか。
    print("ab" * 3)
  7. このコードは何を出力しますか。
    s = "hello"
    s.upper()
    print(s)
    • HELLO
    • hello
    • Hello
    • An error
  8. このコードは何を出力しますか。
    print("rice" in "fried rice")
  9. このコードは何を出力しますか。
    name = "Mina"
    print(f"{name}")
    print("{name}")
    • Mina
      Mina
    • Mina
      {name}
    • {name}
      Mina
    • {name}
      {name}
  10. このコードは何を出力しますか。
    print("Total: " + str(3 * 1000))
    • Total: 3000
    • Total: 3 * 1000
    • Total: 31000
    • An error
よくある間違い
  • 「最初の文字はword[1]。」 インデックスは0から始まるので、word[1]は2番目の文字です。有効な最後のインデックスはlen(word) - 1で、"Python"[6]はIndexError: string index out of rangeで止まります。
  • 「"Age: " + 15はAge: 15を出力する」 文字列とintは+でつなげません。PythonはTypeError: can only concatenate str (not "int") to strで止まります。str(15)かf文字列を使いましょう。
  • 「word[0] = "J"で1文字を直せる。」 文字列はその場で変更できません(TypeError: 'str' object does not support item assignment)。代わりに新しい文字列を組み立てます。たとえば"J" + word[1:]とします。
先生からひとこと0から数えることには、規則ではなく図が要ります。図のように、数字を上と下に付けた箱を描き、何も入力する前に、学習者にword[2]とword[-2]を指させましょう。スライスは、数字を箱に付いたラベルではなく、箱の間の柵と見ると楽になります。upper()の罠(メソッドを呼んで結果を保たない)は、リストでまた現れるので、今、1分かけておきましょう。韓国語のWindowsのフォントでは、バックスラッシュがウォン記号で表示されることがありますが、同じキーで、Pythonにとっても同じ文字です。
ポイント
  • f"...{x}..."は、値を文字の中に入れる。
  • インデックスは0から始まる。-1は最後の文字。
  • s[a:b]は、aから、bは含まずにbの手前まで。
  • upper()のようなメソッドは新しい文字列を返す。元の文字列は変わらない。
  • "\n"は、文字列の中の改行。
このコースの出典 (6)
  • Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
  • Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
  • Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
  • General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
  • Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
  • Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)

確認日: 2026-10-19