ななぶろ

-お役立ち情報を気楽に紹介するブログ-

Pythonプログラム練習問題:文字列操作の基礎と応用(10問)

www.amazon.co.jp

Python プログラム練習問題:文字列操作の基礎と応用 (10問)

Python は、その読みやすさと強力な機能により、初心者からプロフェッショナルまで幅広い層に利用されている人気のプログラミング言語です。特に、文字列操作は、データ処理、Web 開発、自然言語処理など、様々な分野で不可欠なスキルとなります。

本記事では、Python の文字列操作の基礎から応用までを網羅的に解説し、理解度を確認するための練習問題 10 問を用意しました。各問題には、解答例と詳細な解説が含まれており、読者の皆様が Python での文字列処理能力を効果的に向上させることを目指します。

1. 文字列とは?

Python における文字列は、テキストデータを表現するために使用されるデータ型です。文字列は、シングルクォート (') またはダブルクォート (") で囲まれた文字のシーケンスとして定義されます。

string1 = 'Hello, world!'
string2 = "Python is fun."
print(string1)  # Output: Hello, world!
print(string2)  # Output: Python is fun.

文字列はイミュータブル (immutable) であるため、作成後に変更することはできません。文字列の一部を変更するには、新しい文字列を作成する必要があります。

Explanation: In Python, a string is a data type used to represent text data. Strings are sequences of characters enclosed in single quotes (') or double quotes ("). A key characteristic of strings is that they are immutable, meaning their contents cannot be changed after creation. Any modification requires creating a new string object.

2. 基本的な文字列操作

Python は、文字列を操作するための様々なメソッドを提供しています。以下にいくつかの基本的な例を示します。

  • len(): 文字列の長さを返します。 python string = "Hello" length = len(string) print(length) # Output: 5
  • lower(): 文字列を小文字に変換します。 python string = "Hello World" lowercase_string = string.lower() print(lowercase_string) # Output: hello world
  • upper(): 文字列を大文字に変換します。 python string = "Hello World" uppercase_string = string.upper() print(uppercase_string) # Output: HELLO WORLD
  • strip(): 文字列の先頭と末尾にある空白文字を削除します。 python string = " Hello, world! " stripped_string = string.strip() print(stripped_string) # Output: Hello, world!

Explanation: Python offers a variety of methods for manipulating strings. Here are some fundamental examples:

  • len(): Returns the length of the string (number of characters).
  • lower(): Converts the entire string to lowercase.
  • upper(): Converts the entire string to uppercase.
  • strip(): Removes leading and trailing whitespace from a string. This is useful for cleaning up user input or data read from files.

3. 文字列の連結と繰り返し

文字列は、+ 演算子を使用して連結することができます。また、* 演算子を使用して繰り返すこともできます。

string1 = "Hello"
string2 = "World"
concatenated_string = string1 + ", " + string2 + "!"
print(concatenated_string)  # Output: Hello, World!

repeated_string = string1 * 3
print(repeated_string)  # Output: HelloHelloHello

Explanation: Strings can be concatenated (joined together) using the + operator. They can also be repeated multiple times using the * operator. This is useful for building larger strings from smaller components or creating patterns.

4. 文字列のスライス

文字列の一部を取り出すには、スライスを使用します。スライスは、開始インデックスと終了インデックスを指定することで、文字列の特定の部分を抽出することができます。

string = "Python"
substring = string[0:2]  # インデックス 0 から 2 (含まない) まで
print(substring)  # Output: Py

substring = string[2:]  # インデックス 2 から最後まで
print(substring)  # Output: thon

substring = string[:4]  # 最初からインデックス 4 (含まない) まで
print(substring)  # Output: Pyth

substring = string[:]  # 最初から最後まで (文字列全体)
print(substring)  # Output: Python

Explanation: Slicing allows you to extract a portion of a string. You specify the start and end indices to define the substring you want to retrieve. Remember that the end index is exclusive – it means the character at that index will not be included in the slice. Slices create new strings; they don't modify the original string because strings are immutable.

5. 文字列の検索と置換

  • find(): 指定された部分文字列が最初に現れるインデックスを返します。見つからない場合は -1 を返します。 ```python string = "Hello, world!" index = string.find("world") print(index) # Output: 7

    index = string.find("Python") print(index) # Output: -1 ```

  • replace(): 指定された部分文字列を別の文字列に置換します。 python string = "Hello, world!" new_string = string.replace("world", "Python") print(new_string) # Output: Hello, Python!

Explanation: Searching and replacing within strings are common operations.

  • find(): Returns the index of the first occurrence of a substring. If the substring is not found, it returns -1.
  • replace(): Replaces all occurrences of a specified substring with another string. You can also specify a maximum number of replacements to be made.

6. 文字列の分割と結合

  • split(): 指定された区切り文字に基づいて文字列を複数の部分文字列に分割します。 python string = "apple,banana,orange" fruits = string.split(",") print(fruits) # Output: ['apple', 'banana', 'orange']
  • join(): イテラブル (リストなど) の文字列を、指定された区切り文字で結合します。 python fruits = ["apple", "banana", "orange"] string = ",".join(fruits) print(string) # Output: apple,banana,orange

Explanation: Splitting and joining strings are essential for processing data that is stored in string format.

  • split(): Divides a string into a list of substrings based on a specified delimiter (e.g., comma, space).
  • join(): Combines a sequence of strings (like a list) into a single string using a specified separator. The join() method is called on the separator string.

7. 文字列のフォーマット (f-strings)

Python 3.6 以降では、f-strings を使用して文字列を簡単にフォーマットできます。f-strings は、文字列リテラルの中に式を埋め込むことができるため、可読性が高く、効率的です。

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # Output: My name is Alice and I am 30 years old.

Explanation: F-strings (formatted string literals) provide a concise and readable way to embed expressions inside strings. They are prefixed with an f or F. Variables within curly braces {} are evaluated and inserted into the string. This is generally preferred over older formatting methods like % formatting or .format().

8. 文字列の比較

文字列は、== 演算子を使用して比較できます。大文字小文字を区別せずに比較するには、.lower() メソッドを使用します。

string1 = "Hello"
string2 = "hello"
print(string1 == string2)  # Output: False

print(string1.lower() == string2.lower())  # Output: True

Explanation: Strings can be compared for equality using the == operator. To perform a case-insensitive comparison, convert both strings to lowercase (or uppercase) before comparing them.

9. 文字列のエンコーディングとデコード

Python では、文字列は Unicode で表現されます。異なる文字セット (UTF-8, Shift_JIS など) を扱う場合は、エンコーディングとデコードを行う必要があります。

string = "こんにちは"  # Unicode 文字列

# UTF-8 にエンコード
utf8_encoded = string.encode("utf-8")
print(utf8_encoded)  # Output: b'\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf'

# UTF-8 からデコード
utf8_decoded = utf8_encoded.decode("utf-8")
print(utf8_decoded)  # Output: こんにちは

Explanation: Python strings are internally represented using Unicode, which supports a wide range of characters from different languages. However, when you need to store or transmit strings in a file or over a network, they often need to be encoded into a specific character encoding like UTF-8.

  • encode(): Converts a string to bytes using the specified encoding (e.g., "utf-8", "ascii").
  • decode(): Converts bytes back to a string using the specified decoding (e.g., "utf-8", "ascii"). It's crucial to use the correct encoding and decoding for accurate data representation.

10. 文字列のメソッド一覧と参照先

Python の文字列には、様々なメソッドが用意されています。以下に主なものをいくつか示します。

  • capitalize(): 文字列の最初の文字を大文字にし、残りを小文字にします。
  • center(): 指定された幅で中央揃えにします。
  • count(): 指定された部分文字列の出現回数を返します。
  • expandtabs(): タブ文字をスペースに変換します。
  • format(): 文字列をフォーマットします (古い形式)。
  • index(): find() と似ていますが、見つからない場合は ValueError を発生させます。
  • isalnum(): 文字列が英数字のみで構成されているかどうかを返します。
  • isalpha(): 文字列がアルファベットのみで構成されているかどうかを返します。
  • isdecimal(): 文字列が 10 進数として解釈できるかどうかを返します。
  • isdigit(): 文字列が数字のみで構成されているかどうかを返します。
  • islower(): 文字列がすべて小文字であるかどうかを返します。
  • isupper(): 文字列がすべて大文字であるかどうかを返します。
  • lstrip(): 文字列の先頭にある空白文字を削除します。
  • partition(): 指定された区切り文字で文字列を 3 つの部分に分割します。
  • rfind(): find() と似ていますが、右から検索します。
  • rjust(): 指定された幅で右揃えにします。
  • rpartition(): partition() と似ていますが、右から分割します。
  • rstrip(): 文字列の末尾にある空白文字を削除します。
  • splitlines(): 改行文字に基づいて文字列を複数の行に分割します。
  • swapcase(): 大文字と小文字を入れ替えます。
  • title(): 各単語の最初の文字を大文字にします。
  • translate(): 文字列内の文字を別の文字に置換または削除します。

詳細については、Python の公式ドキュメントを参照してください。

Python ドキュメント - str 型

練習問題 (解答と解説は後述)

  1. 文字列 "Hello, world!" の長さを求めなさい。
  2. 文字列 "Python is fun." をすべて大文字に変換しなさい。
  3. 文字列 " Hello, world! " の先頭と末尾の空白を削除しなさい。
  4. 文字列 "apple,banana,orange" を "," で分割し、リストとして取得しなさい。
  5. リスト ["apple", "banana", "orange"] を "," で結合し、文字列として取得しなさい。
  6. 文字列 "Hello, world!" の中に "world" が含まれているか確認し、含まれていればそのインデックスを返せ (含まれていない場合は -1)。
  7. 文字列 "Hello, world!" の中の "world" を "Python" に置換しなさい。
  8. 変数 name = "Alice"age = 30 を使用して、文字列 "My name is Alice and I am 30 years old." を f-string で作成しなさい。
  9. 文字列 "Hello" と "hello" は等しいか (大文字小文字を区別しない)。
  10. 文字列 "こんにちは" を UTF-8 にエンコードし、デコードして元の文字列に戻しなさい。

解答と解説

  1. 解答: len("Hello, world!") 解説: len() 関数は文字列の長さを返します。
  2. 解答: "Python is fun.".upper() 解説: .upper() メソッドは文字列をすべて大文字に変換します。
  3. 解答: " Hello, world! ".strip() 解説: .strip() メソッドは文字列の先頭と末尾にある空白文字を削除します。
  4. 解答: "apple,banana,orange".split(",") 解説: .split(",") メソッドは、文字列を "," で分割し、リストとして返します。
  5. 解答: ",".join(["apple", "banana", "orange"]) 解説: ",".join() は、リストの要素を "," で結合して文字列を作成します。
  6. 解答: "Hello, world!".find("world") 解説: .find() メソッドは指定された部分文字列が最初に現れるインデックスを返します。見つからない場合は -1 を返します。
  7. 解答: "Hello, world!".replace("world", "Python") 解説: .replace() メソッドは、指定された部分文字列を別の文字列に置換します。
  8. 解答: f"My name is {name} and I am {age} years old." 解説: f-string は、変数名を {} で囲むことで、文字列の中に埋め込むことができます。
  9. 解答: False (大文字小文字を区別する場合) / True (大文字小文字を区別しない場合) 解説: 文字列の比較はデフォルトで大文字小文字を区別します。.lower() メソッドを使用すると、大文字小文字を区別せずに比較できます。
  10. 解答: python string = "こんにちは" utf8_encoded = string.encode("utf-8") utf8_decoded = utf8_encoded.decode("utf-8") print(utf8_decoded) 解説: .encode() メソッドは文字列を特定のエンコーディングでエンコードし、.decode() メソッドはエンコードされたバイト列を元の文字列にデコードします。

まとめ

本記事では、Python の文字列操作の基礎から応用までを網羅的に解説しました。練習問題を通して、皆様が Python での文字列処理能力を効果的に向上させられることを願っています。 文字列操作は、プログラミングにおいて非常に重要なスキルです。ぜひ、これらの知識とテクニックを活用して、より効率的で洗練されたコードを作成してください。