1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🐍 Python入門:変数と文字列の基本

Posted at

はじめに

Pythonプログラミングにおいて、データ(値)を格納し、操作するための基本となるのが「変数」と「文字列(String)」です。ここでは、チートシートの内容を参考に、これらの使い方を具体的なコード例とともに解説します。


1. 変数 (Variables)

変数は、値を記憶するための「名前付きの箱」のようなものです。

📌 割り当てと出力

Action (操作) 説明 Example (例)
Assign a value to a variable 変数に値を割り当てる message = "Hello, World!"
Print the value 変数に格納された値を出力する print(message)

📝 プログラムソース

# 変数 'message' に文字列 "Hello, World!" を代入
message = "Hello, World!"

# 変数 'message' の値を出力
print(message) 
# 出力: Hello, World!

# 変数の値は上書き可能
message = "Goodbye, Python."
print(message)
# 出力: Goodbye, Python.

2. 文字列 (Strings)

文字列は、文字の並び(テキストデータ)を扱うデータ型です。Pythonでは、シングルクォート (') またはダブルクォート (") で囲んで表現します。

📌 文字列の操作 (String methods)

Pythonの文字列には、値を変更したり、情報を取得したりするための便利な「メソッド(操作)」が用意されています。

String methods (文字列メソッド) 説明 Example (例)
Lowercase すべての文字を小文字に変換する message.lower()
Uppercase すべての文字を大文字に変換する message.upper()
Title Case 各単語の先頭の文字を大文字に変換する(タイトル形式) message.title()
Remove whitespace 文字列の両端にある空白(スペース、タブ、改行など)を削除する message.strip()

📝 プログラムソース

name = "aLiCE sMith"
text = "    Hello World!    \n"

# 1. 大文字・小文字変換
print(f"元の文字列: {name}") 
print(f"大文字に変換: {name.upper()}") 
# 出力: ALICE SMITH

print(f"小文字に変換: {name.lower()}")
# 出力: alice smith

print(f"タイトル形式に変換: {name.title()}")
# 出力: Alice Smith


# 2. 空白の除去
print("---")
print(f"元の文字列 (前後に空白あり): '{text}'")
print(f"空白を除去した文字列: '{text.strip()}'")
# 出力: 'Hello World!'
# ※ .strip() は文字列の内部にある空白(例: 'Hello  World'の二重スペース)は削除しません。

💡 まとめと次のステップ

  • 変数は、データを格納する名前であり、代入演算子 (=) を使って値を設定します。
  • 文字列は、テキストデータであり、様々なメソッドを使って整形・操作できます。特に .lower(), .upper(), .title(), .strip() は頻繁に使われます。

これらの基本を習得すれば、データの管理と表示に関する基礎はバッチリです!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?