0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python tips1 ~ 文字列操作

Last updated at Posted at 2018-09-18

python tipsと題して、備忘録的にPythonのコードをまとめていく。今回は文字列操作について、ただし正規表現は扱わない(正規表現は苦手でこれから勉強していかないと。。。)

文字列の連結

s = 'hello world'
## 連結
s + "!!!" # > hello world!!!
## 連続で連結
s + "!" * 3 # > hello world!!!

分割

s = 'hello world'
s.split(' ') # >> ['hello', 'world']

文字列の長さ

s = 'hello world'
len(s) # >> 11

文字列の抜き出し

s = 'hello world'
s[0] # >> h
s[-1] # >> d
s[:5] # >> hello
s[:-3] # >> hello wo
s[2:5] # >> llo

文字列の桁揃え

s = 'hello world'
## 文字列の桁揃え
ss = '1234'
ss.rjust(10, '0') # >> 0000001234
ss.rjust(10, '!') # >> !!!!!!1234
## 文字列の桁揃え >> 0指定
ss = '1234'
ss.zfill(10) # >> 0000001234

検索

文字列が含まれているかを判定

s = 'hello world'
'e' in s # >> True

文字列を検索し、存在していた場合先頭文字のインデックスを返す


s = 'hello world'
s.find('wor') # >> 6

文字列の先頭が一致しているかどうかを判定

s = 'hello world'
startswith('hello') # >> True

文字列の後方が一致しているかどうかを判定

s = 'hello world'
s.endswith('ld') # >> True

置換

s = 'hello world'
s.replace('h', 'H') # >> Hello world

大文字 ⇔ 小文字

s = 'HELLO WORLD'
s_low = s.lower() # >> hello world
s_upper = s.upper() # >> HELLO WORLD
0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?