Contents
4.2文字列を扱う
では、Pythonで文字列(string)を扱う方法を
初心者向けに、実例中心で解説します。
文字列とは?
文字列とは
👉 **文字の並び(文章・単語・記号など)**を表すデータ型です。
s = "Hello"
t = 'Python'
ダブルクォート ” ”
シングルクォート ‘ ‘
👉 どちらでもOK
文字列の表示(print)
name = "太郎"
print(name)
(実行結果)
太郎
文字列の連結(つなげる)
a = "Hello"
b = "World"
print(a + " " + b)
(実行結果)
Hello World
👉 + で文字列をつなげる
数字と文字列はそのままでは混ぜられない
❌ エラー例
age = 20
print(“年齢は” + age)
⭕ 正しい例
print(“年齢は” + str(age))
👉 数字 → 文字列に変換:str()
f文字列(最重要・おすすめ)
age = 20
print(f"年齢は{age}歳です")
✅ f は f文字列(f-string) を表します。文字列の中に変数を埋め込める仕組みです
👉 Pythonで最も使われる書き方
👉 見やすく、間違いにくい
※古い書き方(+でつなぐ)は面倒だった
print("年齢は" + str(age) + "歳です")
※変数だけでなく「計算」もできる
x = 5
print(f"2倍は{x*2}")
→2倍は10
文字列の長さを調べる
s = "Python"
print(len(s))
→6
文字列の一部を取り出す(インデックス)
s = "Python"
print(s[0])
print(s[1])
(実行結果)
P
y
0から始まる(重要)
マイナスも使える
print(s[-1]) # 最後の文字
文字列のスライス
s = "Python"
print(s[0:3])
(実行結果)
Pyt
書式:
文字列[開始:終了]
※ 終了位置は 含まれない
よく使う文字列メソッド
s = "hello python"
処理 書き方 結果
大文字 s.upper() HELLO PYTHON
小文字 s.lower() hello python
置換 s.replace("python", "world") hello world
分割 s.split() ['hello', 'python']
入力(input)は文字列になる(重要)
x = input("入力してください:")
print(type(x))
<class 'str'>
👉 数字として使う場合は変換が必要
n = int(input("数字を入力:"))
エスケープ文字(特殊文字)
print("こんにちはnPython")
記号 意味
n 改行
t タブ
" " を表示
まとめ(必須ポイント)
文字列: ‘ ‘ または ” ”
連結: +
表示: print()
変数埋め込み: f文字列
入力: input() は文字列
変換: str() / int()

コメント