【Python】文字列を優雅に扱う方法 (1)

[Python] 文字列を処理する実用的な単純なケース

1.最初の文字を大文字にする

***str.capitalize()*** メソッドを使用して、文字列の最初の文字を大文字に変換します。

string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)  
# 输出 "Hello world"

2.区切り文字に従って文字列をリストに分割します

***str.split()*** メソッドを使用して、指定された区切り文字に従って文字列をリストに分割します。区切り文字が指定されていない場合、デフォルトでスペースが使用されます。

string = "apple,orange,banana"
fruits_list = string.split(",")
print(fruits_list)  
# 输出 ["apple", "orange", "banana"]

3. 文字列を連結して新しい文字列にする

***str.join()*** メソッドを使用して、文字列 (またはその他の反復可能なオブジェクト) のリストの要素を新しい文字列に連結します。このメソッドのパラメーターは反復可能なオブジェクトで、各要素は連結される文字列です。

fruits_list = ["apple", "orange", "banana"]
joined_string = ",".join(fruits_list)
print(joined_string)  
# 输出 "apple,orange,banana"

4.文字列内のスペースを削除します

***str.strip()*** メソッドを使用して、文字列の先頭と末尾のスペースを削除します。文字列の途中にあるスペースを削除する必要がある場合は、str.replace() メソッドを使用できます。

string = "  hello world  "
stripped_string = string.strip()
print(stripped_string)  
# 输出 "hello world"

strip() が追加されました:

strip() 関数を使用して、文字列 (デフォルトはスペースまたは改行) または一連の文字の先頭と末尾にある指定された文字を削除できます; 注: このメソッドは先頭または末尾の文字のみを削除でき
ます。途中の文字ではありません

# 只要头尾包含有指定字符序列中的字符就删除
id_list = [1, 2, 3, 4]
sql = f"select * from user where 1 = 1 and id in ({
      
      str(id_list).strip('[]')})"
print(sql) 
# 输出 "select * from user where 1 = 1 and id in (1, 2, 3, 4)"

5.文字列のフォーマット

方法 1: ***str.format()*** メソッドを使用して、文字列内のプレースホルダーを指定された値に置き換えます。プレースホルダーは、中かっこ {} のペアで表され、パラメーター名、フォーマット方法、およびその他の情報を指定できます。

name = "Alice"
age = 25
formatted_string = "My name is {} and I'm {} years old.".format(name, age)
print(formatted_string)  
# 输出 "My name is Alice and I'm 25 years old."

方法 2: Python の f 文字列。変数を中かっこ {} で囲み、先頭に文字 "f" を付けて、これが書式設定された文字列であることを示します。

name = "Alice"
age = 25
formatted_string = f"My name is {
      
      name} and I'm {
      
      age} years old."
print(formatted_string)  
# 输出 "My name is Alice and I'm 25 years old."

おすすめ

転載: blog.csdn.net/yqyn6/article/details/129810555
おすすめ