文字列とブール値の操作
数値データ型に加えて、Python はテキストデータ用の文字列 (string) と真偽値用のブール値 (boolean) を提供しています。これらの型について調べてみましょう。
-
WebIDE で /home/labex/project/variables.py
ファイルを開きます。
-
以下のコードを追加して、文字列とブール値の変数を定義します。
## String data type - for text
camp_name = "Python Base Camp"
location = 'Programming Valley' ## Strings can use single or double quotes
## Boolean data type - for true/false values
is_safe = True
has_water = True
enemy_nearby = False
- これらの変数をチェックして表示するコードを追加します。
## Displaying string and boolean variables
print("\nString variables:")
print("Camp name:", camp_name, "- Type:", type(camp_name))
print("Location:", location, "- Type:", type(location))
print("\nBoolean variables:")
print("Is the camp safe?", is_safe, "- Type:", type(is_safe))
print("Is water available?", has_water, "- Type:", type(has_water))
print("Is enemy nearby?", enemy_nearby, "- Type:", type(enemy_nearby))
- いくつかの文字列操作も実演しましょう。
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)
## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
- スクリプトを実行します。
python3 /home/labex/project/variables.py
以下のような出力が表示されるはずです。
Water supply: 100
Food supply: 50
Ammunition: 40
Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>
Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678
String variables:
Camp name: Python Base Camp - Type: <class 'str'>
Location: Programming Valley - Type: <class 'str'>
Boolean variables:
Is the camp safe? True - Type: <class 'bool'>
Is water available? True - Type: <class 'bool'>
Is enemy nearby? False - Type: <class 'bool'>
Full location: Python Base Camp in Programming Valley
--------------------
Camp Information
--------------------
文字列は +
演算子で連結でき、*
演算子で繰り返すことができることに注意してください。ブール値は条件を表現し、プログラムの流れを制御するのに便利です。