【Python】Python ~ 基本編 / 文字列 ~

■ はじめに

Pythonの文字列のメモ書き

目次

【1】文字列操作
【2】文字列の比較
【3】標準入力
【4】文字列のフォーマット指定
 1)format
 2)f-strings
 3)% 演算子
【5】文字列定数
【6】大文字 / 小文字の変換
 1)upper
 2)lower
 3)capitalize
【7】文字列化
【8】Trim(文字列除去)
【9】ゼロ埋め
【10】改行有の文字列(トリプルクォート)

【1】文字列操作

* 長くなったので、分冊。以下の関連記事を参照のこと。

Python ~ 基本編 / 文字列操作 ~
https://dk521123.hatenablog.com/entry/2023/10/20/000000

【2】文字列の比較

* 長くなったので、分冊。以下の関連記事を参照のこと。

https://dk521123.hatenablog.com/entry/2021/07/29/000000

【3】標準入力

* input() を使う

https://note.nkmk.me/python-input-usage/

サンプル

answer = input("Please input Y/n : ")
print(answer)
answer = answer.upper()

if answer == 'Y' or answer == 'YES':
  print("Yes")
else:
  print("No")

print("Done")

出力結果

# ”yes”を入力
Please input Y/n : yes
yes
Yes
Done

# ”no”を入力
Please input Y/n : no
no
No
Done

 【4】文字列のフォーマット指定

1)format
2)f-strings
3)% 演算子

 1)format

* 可変部を{}にする

サンプル

# 「日本の首都は東京です」と出力
print("{}の首都は{}です".format("日本", "東京"))

# 「それはそれ, これはこれ」と出力
print("{A1}は{A1}, {A2}は{A2}".format(A1="それ", A2="これ"))

# ゼロ埋め
print("{:0=2}_hello_{:0=3}.txt".format(1, 1))
# 01_hello_001.txt

補足:波括弧のエスケープ

# 波括弧を重ねる({date}をエスケープしたい場合)
print("/{val1}/{val2}/{{date}}".format(val1="path1", val2="path2"))

https://qiita.com/FGtatsuro/items/a64066e2151203b7221a

2)f-strings

https://www.youtube.com/watch?v=MLronWYaHw8

で使ってて便利そうだったので調べてみた。

* From Python3.6
* 読み方もそのまま「エフ-ストリングス」
* format()をより簡単に書ける

https://note.nkmk.me/python-f-strings/

サンプル

name = "Mike"
print(f"Hello, {name}") # Hello, Mike

result = f"Hello, {name}"
print(result) # Hello, Mike

 3)% 演算子

 * %d   : 整数で表示
 * %f   : 小数で表示
 * %.3f : 小数第3位まで表示
 * %s   : 文字列として表示

サンプル

if __name__ == '__main__':
 pi = 3.141592
 # 小数点第4位まで表示
 print("PI is %.4f !" % pi)

 host = 'localhost'
 port = 8080
 user = 'admin'
 password = 'password1'
 result = "host=%s port=%d user=%s pass=%s" % (
   host, port, user, password)
 print(result)

出力結果

PI is 3.1416 !
host=localhost port=8080 user=admin pass=password1

【5】文字列定数

文字列に関する定数

https://docs.python.org/ja/3/library/string.html

サンプル

import string

alphabet = string.ascii_uppercase
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(alphabet)
alphabet = string.ascii_lowercase
# abcdefghijklmnopqrstuvwxyz
print(alphabet)
alphabet = string.ascii_letters
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(alphabet)

【6】大文字 / 小文字の変換

https://note.nkmk.me/python-capitalize-lower-upper-title/

が参考になる

1)upper

* 大文字にする

2)lower

* 小文字にする

3)capitalize

* 先頭の一文字を大文字、他を小文字に変換

サンプル

city="Tokyo"
big_city=city.upper()
print(big_city)

 【7】文字列化

* str() を使う

サンプル

number = 1
print("あなたは" + str(number) + "位です")

【8】Trim(文字列除去)

* 長くなったので、以下の関連記事にまとめなおした。
 => ちなみに「<文字列>.trim()」じゃない

cf. trim = ~を刈り込む、(予算などを)削減する

https://dk521123.hatenablog.com/entry/2021/06/07/164858

【9】ゼロ埋め

num = 8

# 00008
print(str(num).zfill(5))

参考文献

https://docs.python.org/ja/3/library/stdtypes.html#str.zfill

【10】改行有の文字列(トリプルクォート)

* 「\n」でもできるが、トリプルクォート ''', """ が便利。

サンプル

targets = {
  "Mike": "14",
  "Tom": "23",
  "Sam": "34",
  "Kevin": "45",
}
# ★注目★
template = """
- age: {age}
  name: "{name}"
"""

file_content = ""
for index, (key, value) in enumerate(targets.items()):
  setting = template.format(
    age=value,
    name=key
  )
  file_content = file_content + setting.lstrip()

print(file_content)
with open('hello_out.yaml', mode='w') as file:
  file.write(file_content)

関連記事

Python ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/08/07/231242
 Pythonで セキュアなランダム文字列生成を考える
https://dk521123.hatenablog.com/entry/2021/11/29/110408

Python ~ 基本編 ~

bool
https://dk521123.hatenablog.com/entry/2021/10/02/000000
先頭・末尾の文字列除去
https://dk521123.hatenablog.com/entry/2021/06/07/164858
Python ~ 基本編 / 文字列操作 ~
https://dk521123.hatenablog.com/entry/2023/10/20/000000
文字列比較
https://dk521123.hatenablog.com/entry/2021/07/29/000000
繰り返し
https://dk521123.hatenablog.com/entry/2019/08/25/000330
条件分岐
https://dk521123.hatenablog.com/entry/2020/07/17/000000
コメント文
https://dk521123.hatenablog.com/entry/2019/10/23/212149
関数
https://dk521123.hatenablog.com/entry/2019/09/22/000000
関数・あれこれ
https://dk521123.hatenablog.com/entry/2020/11/02/000000
global・nonlocal
https://dk521123.hatenablog.com/entry/2019/12/12/232749
yield
https://dk521123.hatenablog.com/entry/2021/03/18/000000
クラス・継承
https://dk521123.hatenablog.com/entry/2019/08/29/220537
抽象クラス
https://dk521123.hatenablog.com/entry/2021/11/28/113711
日付・日時
https://dk521123.hatenablog.com/entry/2019/10/14/121909
日付・日時あれこれ
https://dk521123.hatenablog.com/entry/2022/02/01/000000
スライス操作
https://dk521123.hatenablog.com/entry/2020/11/14/000000
リスト
https://dk521123.hatenablog.com/entry/2019/10/12/084943
リスト・あれこれ
https://dk521123.hatenablog.com/entry/2020/11/01/000000
辞書
https://dk521123.hatenablog.com/entry/2019/10/27/100014
辞書・あれこれ
https://dk521123.hatenablog.com/entry/2020/10/11/000000
タプル
https://dk521123.hatenablog.com/entry/2019/10/26/000000
集合 Set
https://dk521123.hatenablog.com/entry/2021/04/02/000000
Enum
https://dk521123.hatenablog.com/entry/2019/11/26/234736
ラムダ lambda
https://dk521123.hatenablog.com/entry/2019/09/23/000000
map
https://dk521123.hatenablog.com/entry/2021/03/29/000000
例外処理
https://dk521123.hatenablog.com/entry/2019/08/03/000000
正規表現
https://dk521123.hatenablog.com/entry/2019/09/01/000000
正規表現あれこれ
https://dk521123.hatenablog.com/entry/2020/10/15/000000
標準入力 input
https://dk521123.hatenablog.com/entry/2019/08/02/000000
コマンドライン引数
https://dk521123.hatenablog.com/entry/2019/10/11/223651
パッケージ化
https://dk521123.hatenablog.com/entry/2019/09/21/000000
フォルダ・ファイル操作
https://dk521123.hatenablog.com/entry/2019/09/02/000000
パス情報抽出
https://dk521123.hatenablog.com/entry/2022/02/23/000000
ファイル圧縮/解凍
https://dk521123.hatenablog.com/entry/2019/09/03/000000
ファイル読込・書込
https://dk521123.hatenablog.com/entry/2019/10/07/000000
CSV
https://dk521123.hatenablog.com/entry/2019/11/07/214108
YAML
https://dk521123.hatenablog.com/entry/2019/10/16/225401
JSON
https://dk521123.hatenablog.com/entry/2019/10/19/104805
JSONあれこれ
https://dk521123.hatenablog.com/entry/2022/02/14/000000
Python ~ TOML ~
https://dk521123.hatenablog.com/entry/2024/01/27/000110
urllib
https://dk521123.hatenablog.com/entry/2022/08/05/000000
astモジュール
https://dk521123.hatenablog.com/entry/2021/10/01/000000
Excelを扱う・OpenPyXL
https://dk521123.hatenablog.com/entry/2020/08/27/000000
シリアライズ・デシリアライズ
https://dk521123.hatenablog.com/entry/2019/10/06/000000
ジェネリック
https://dk521123.hatenablog.com/entry/2019/12/11/231948
型指定・Typing
https://dk521123.hatenablog.com/entry/2021/12/23/231559
eval, exec
https://dk521123.hatenablog.com/entry/2020/05/15/140053
外部コマンド実行 ~
https://dk521123.hatenablog.com/entry/2021/08/04/224716
Python再帰関数 ~
https://dk521123.hatenablog.com/entry/2023/06/11/000000
Python ~ 画像処理 / Pillow ~
https://dk521123.hatenablog.com/entry/2023/07/10/000000
Python + DOT言語で図作成するには
https://dk521123.hatenablog.com/entry/2023/06/14/174104
Python ~ PDF ~
https://dk521123.hatenablog.com/entry/2023/07/19/001703
Python ~ デコレータ @xxxx ~
https://dk521123.hatenablog.com/entry/2020/05/19/000000
Python ~ 可変長引数 / *args kwargs ~ **
https://dk521123.hatenablog.com/entry/2023/11/01/000915