Skip to content

Instantly share code, notes, and snippets.

@yuuichi-fujioka
Last active December 16, 2015 05:39
Show Gist options
  • Save yuuichi-fujioka/5386040 to your computer and use it in GitHub Desktop.
Save yuuichi-fujioka/5386040 to your computer and use it in GitHub Desktop.
python 文字列のいろいろ
# combine
'foo' + 'bar' # foobar
'foo' 'bar' # foobar
# split
'hello world'.split() # ['hello', 'world']
'|foo|bar|'.split('|') # ['', 'foo', 'bar', '']
'alice, bravo, scot, tiger'.split(',', 2) # ['alice, 'bravo', 'scot, tiger']
# ゼロ埋め
'%03d'%(10) # 010
# last index of
'/hoge/fuga'.rfind('/') # 5
# ~with
'red'.startswith('s') # True
'blue'.endswith('e') # True
# substring
'hoge'[-2:] # ge
'fuga'[1:] # uga
'scott'[2:4] #ot
'tigger'[:-3] # tig
# strlen
len('hoge') # 4
# formatting
'this is %s'%('pen') # this is pen
'this is %(item)s. %(item)s is %(color)s'%{'item':'pen','color':'red'} # this is pen. pen is red
# centering
'foo'.center(9, '_') # ___foo___
# trim
' foo bar '.strip() # foo bar
# read lines
import StringIO
txt = '''aaa
bbb
ccc
ddd'''
buf = StringIO.StringIO(txt)
for line in buf:
print line[:-1]
# aaa
# bbb
# ccc
# ddd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment