0
1

Pythonの便利技と注意点:文字列編

Last updated at Posted at 2022-08-25

目次に戻る

raw文字とフォルダパス記述

raw文字:フォルダパスで使う時に便利
>>> print(r'C:\Program Files\fnord')
C:\Program Files\fnord
但し、文字列の最後に「\」を入れるとエラーになる
>>> print(r'C:\Program Files\')
  File "<stdin>", line 1
    print('C:\Program Files\')
                             ^
SyntaxError: EOL while scanning string literal
最後に\を入れたい場合は、分けて記載する
>>> print(r'C:\Program Files' '\\')
C:\Program Files\
Windowsのパスでもバックスラッシュor円マークではなく/で代替するのもアリ
>>> import os
>>> path = r'C:/Program Files/7-Zip'
>>> flist = os.listdir(path)
>>> print(flist)
['7-zip.chm', '7-zip.dll', '7-zip32.dll', '7z.dll', '7z.exe', '7z.sfx', '7zCon.sfx', '7zFM.exe', '7zG.exe', 'descript.ion', 'History.txt', 'Lang', 'License.txt', 'readme.txt', 'Uninstall.exe']
Windowsのパスを/に代替する場合、rなしでもOK
>>> import os
>>> path = 'C:/Program Files/7-Zip'
>>> flist = os.listdir(path)
>>> print(flist)
['7-zip.chm', '7-zip.dll', '7-zip32.dll', '7z.dll', '7z.exe', '7z.sfx', '7zCon.sfx', '7zFM.exe', '7zG.exe', 'descript.ion', 'History.txt', 'Lang', 'License.txt', 'readme.txt', 'Uninstall.exe']

文字列を簡単にListに入れる

文字列をリストに変換すると一文字ずつ「''」で囲わなくて便利
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']

>>> list('12345')
['1', '2', '3', '4', '5']
文字列リストを本来の並びに戻したい場合はjoin
>>> l = list('Hello')
>>> l
['H', 'e', 'l', 'l', 'o']
>>> ''.join(l)
'Hello'

テンプレート文字列:Template()とsubstitute()

format()やf''以外の方法で表示する
>>> from string import Template
>>> tmpl = Template("こんにちは、$whoさん、$whatですか?")
>>> tmpl.substitute(who="一郎", what="お元気")
'こんにちは、一郎さん、お元気ですか?'
>>> tmpl.substitute(who="二郎", what="ご機嫌いかが")
'こんにちは、二郎さん、ご機嫌いかがですか?'

英単語の先頭文字だけを大文字にするtitle()とcapwords()

title()だと’の後の文字も大文字にしてしまう
>>> "let's call it a day!".title()
"Let'S Call It A Day!"
capwords()の方が便利
>>> import string
>>> string.capwords("let's call it a day!")
"Let's Call It A Day!"

文字コードを知る方法

ord()を使うとその文字のコードを返してくれる
>>> ord("A")
65
>>> ord("a")
97
>>> ord("")
12354
>>> ord("")
34678
chr()にコードを入れるとその文字を返してくれる
>>> chr(65)
'A'
>>> chr(97)
'a'
>>> chr(12354)
''
>>> chr(34678)
''

文字列を一定文字数ごとに改行する技

添え字+1ごとに"\n"を追加する
>>> aiueo = 'あいうえおかきくけこさしすせそたちつてとなにぬねの'
>>> s = ''
>>> for i in range(len(aiueo)):
	s += aiueo[i]
	if (i>0) and ((i+1) % 5 == 0):
		s += "\n"		
>>> print(s)
あいうえお
かきくけこ
さしすせそ
たちつてと
なにぬねの

文字列を何文字目か1文字だけ変える技

文字列を1つだけ入れ替えようとしても不変なのでエラーが出る
Char_A = 'Apple'
Char_A[0] = 'a'
print(Char_A)
================
TypeError: 'str' object does not support item assignment
文字列をリスト化すれば入れ替えられる
# 文字列をlist化して格納
# [['A', 'p', 'p', 'l', 'e'], ['O', 'r', 'a', 'n', 'g', 'e']]
Char_A = []
Char_A.append(list('Apple'))
Char_A.append(list('Orange'))

# list化された文字列の該当箇所を指定して交換
Char_A[0][0] = 'a'
Char_A[1][0] = 'o'

# listから各文字をくっつけて取り出す
for i in range(len(Char_A)):
    print("".join(Char_A[i]))
==============================================================
apple
orange

目次に戻る

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1