Pythonの文字列処理の基本

この記事で解決すること

pythonの文字列処理の基本を思い出せます。

この記事の想定読者

  • pythonの文字列処理を忘れた方
  • python初心者の方
  • 自分自身の備忘録

目次

Pythonの文字列処理

文字列の括りは ' と " のどちらでも良い

text1 = 'テキストデータ1'
text2 = "テキストデータ2"

print(text1)
print(text2)
テキストデータ1
テキストデータ2

文字列に改行を入れる時

print('「テキスト\nデータ」\n')
print('「テキ\nスト\nデー\nタ」\n')
「テキスト
データ」

「テキ
スト
デー
タ」
print('''「テキスト
データ」
''')
print("""「テキスト
データ」
""")
「テキスト
データ」

「テキスト
データ」

文字列から、1文字だけ取り出すには

text = "Software Design"
print(text[0])
print(text[1])
S
o
text = "Software Design"
print(text[-1])
print(text[-2])
n
g
text = "Software Design"
print(text[0:8])
print(text[-11:-7])
print(text[:8])
print(text[9:])
print(text[:])
Software
ware
Software
Design
Software Design

文字列の分割

text = '''生徒1 10,20,30
生徒2 40,30,20
生徒3 25,30,40
'''

lines = text.splitlines()
print(lines)
['生徒1 10,20,30', '生徒2 40,30,20', '生徒3 25,30,40']
scores =[]
for line in lines:
  student = line.split()
  scores.append([student[0], student[1].split(',')])

print(scores)
[['生徒1', ['10', '20', '30']], ['生徒2', ['40', '30', '20']], ['生徒3', ['25', '30', '40']]]

文字列のフォーマット

for score in scores:
  print(f"{score[0]}の平均点は、{(int(score[1][0])+int(score[1][1])+int(score[1][2]))/3:3.1f}")     
生徒1の平均点は、20.0
生徒2の平均点は、30.0
生徒3の平均点は、31.7
最後の f

指定した精度で表現できない数字の場合は、123.456 のような固定小数点表記ではなく、123456e-3 のような指数表記で出力されます。

書式の最後に f をつけると固定小数点表記、e をつけると指数表記で出力されます。

print(f"|{'左寄せ':<8}|{'中央寄せ':^8}|{'右寄せ':>8}|")
|左寄せ     |  中央寄せ  |     右寄せ|
sales = [149820000, 253000, 9822, 91273000]

print(f'''{"年度":<5} | {"売上":^10}
--------+--------------
{2015:<7} | {sales[0]:12,}
{2016:<7} | {sales[1]:12,}
{2017:<7} | {sales[2]:12,}
{2018:<7} | {sales[3]:12,}
年度    |     売上    
--------+--------------
2015    |  149,820,000
2016    |      253,000
2017    |        9,822
2018    |   91,273,000
value = 160
print(f'''
2進数: {value:8b}
8進数: {value:8o}
10進数:{value:8d}
16進数:{value:8x}
''')
2進数: 10100000
8進数:      240
10進数:     160
16進数:      a0
デバッグに便利なフォーマット (3.8以降)

foo = 10; bar = 20
print(f'{foo=} {bar = } {foo + bar = }')
foo=10 bar = 20 foo + bar = 30

参考

  • Software Design 2020年2月号 Pythonの文字列処理の基本

プログラム開発

Posted by iwadjp