3.1. 文字列

3.1.1. 文字列の入力・表示

Python3では文字列をコンソールに表示するには print()関数を使います

1
print('Hello World')

出力

Hello World

3.1.2. 複数行文字列の入力・表示

Pythonでは複数行を含む文字列を書くことができます。 その場合ダブルクオートを3つ繋げたもので文字列を括ります。

1
2
3
4
5
6
test = """
Hello World

Python
"""
print(test)

出力

Hello World

Python

3.1.3. 文字列の連結

文字列どうし、文字列と変数などは連結させて表示することができます。

1
2
3
test = 'Hello Python'
test = test+' of the world'
print(test)

出力

Hello Python of the world

後から必要な分追加するのも可能です。

1
2
3
4
5
test = 'abc'
test += 'def'
test += 'ghi'

print(test)

出力

abcdefghi

3.1.4. 文字列の変換

Python3では数値と文字列を結合する場合にはstrを使用します

1
2
3
4
int1 = 123    #数値には''はいりません
test = 'start' + str(int1)

print(test)

出力

start123

3.1.5. 文字列の置換

文字列を置換する場合にはreplace(\'置換前の文字列\',\'置換後の文字列\')とします

1
2
3
test = "kyakyukyo"

print(test.replace('ky', 'ch'))

出力

chachucho

3.1.6. 文字列の分割

文字列の分割はsplit(\'分割するルールとなる文字列\')とします

1
2
3
test = 'start-2017-11-10'

print(test.split('-'))

出力

['start','2017','11','10']

3.1.7. 文字列の桁揃え

文字列の桁揃えをする場合はrjust(桁数,\'埋め込む文字列\')

1
2
3
test = '146'

print(test.rjust(10,x))

出力

xxxxxxx146

なお0で埋めたい時にはzfill(桁数)とすれば0で埋まります。

1
2
3
test = '146'

print(test.zfill(10))

出力

0000000146

3.1.8. 文字列の検索

文字列の検索をする場合は様々ですが、まずは文字列の先頭が任意の文字であるかを調べるにはstartswith(\'検索したい文字列\') で先頭が任意の文字であるかないかを判断できます。 返り値はTrueかFalseです。

1
2
3
4
test = 'Hello Python!'

print(test.startswith('Hello'))
print(test.startswith('Python'))

出力

True
False

なお文字列の中の任意の文字が含まれているかどうかは \'任意の文字列\' in 変数 とすることで調べられます。

1
2
3
4
test = 'Hello Python!'

print('e' in test)
print('j' in test)

出力

True
False

3.1.9. 文字列の大文字・小文字変換

文字列の変換には 変数.upper() または 変数.lower()を使います。

1
2
3
4
test = 'Hello Python'

print(test.upper())
print(test.lower())

出力

HELLO PYTHON
hello python

3.1.10. 先頭・末尾の削除

文字列の先頭・末尾を削除した値を取得します。 それぞれ「lstrip」は先頭(左から)、「rstrip」は末尾(右から)の削除となり、引数なしでは空白を除去します。 ※末尾の空白の削除は出力結果ではわかりづらいので、スラッシュを付加しています。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
print('-----------------------')

test = '             python3'
print(test)

test = test.lstrip();
print(test)

print(test.lstrip('python'))

print('-----------------------')

test = 'python3           '
print(test + '*')

test = test.rstrip()
print(test+ '*')

test = test.rstrip('on3')
print(test)

出力

-----------------------
             python3
python3
3
-----------------------
python3          *
python3*
pyth