Last active
December 16, 2015 05:39
-
-
Save yuuichi-fujioka/5386040 to your computer and use it in GitHub Desktop.
python 文字列のいろいろ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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