f 文字列 (f-String)
t = f'I am {name}.'
長い文字列を改行
t = ('aaaaaaaaaaaaaaaaaaa'
'bbbbbbbbbbbbbbbbbbbb'
+ f'I am {name}.'
'ccccccccccccccccccc')
任意の文字列を含むか判定
s = 'I am Sam'
print('Sam' in s)
# True
print('sam' in s)
# False
print('I' in s and 'Sam' in s)
# True
文字列の分割・置換
txt = 'aaa-bbb-ccc-ddd'
txt1 = txt.split('-')
print(txt1)
# ['aaa', 'bbb', 'ccc', 'ddd']
txt2 = txt.partition('-')
print(txt2)
# ('aaa', '-', 'bbb-ccc-ddd')
txt3 = txt.replace('-', ' ')
print(txt3)
# aaa bbb ccc ddd
文字列を指定して置換: replace
s = 'one two one two one'
print(s.replace(' ', '-'))
# one-two-one-two-one
文字列を行ごとに分割してリスト化
txt = 'aaa\nbbb\nccc\nddd'
splitTxt = txt.splitlines()
print(splitTxt)
# ['aaa', 'bbb', 'ccc', 'ddd']
文字列の一部を削除
特定の文字以降を削除
txt = 'abc-def'
txt = txt.split('-')[0]
最後の1文字を削除
txt = 'あいうえお'
txt = txt[:-1]
ランダムな文字列を生成
import random, string
def randomname(n):
return ''.join(random.choices(string.ascii_letters + string.digits, k=n))
print(randomname(16)) #16文字で生成
# Bjr06LKcHM8XRfxz
全角を半角に統一
def zenkaku_to_hankaku(text):
return text.translate(str.maketrans({chr(0xFF01 + i): chr(0x21 + i) for i in range(94)}))
text = "!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`>?@abcdefghijklmnopqrstuvwxyz{|}~"
print(zenkaku_to_hankaku(text))
# '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`>?@abcdefghijklmnopqrstuvwxyz{|}~'