【Python】文字列から文字を取り出す
[数字]の書式で文字列の特定場所の文字を取り出すことができます。
0から始まることに注意が必要です。
1 2 3 4 5 6 7 8 9 10 |
>>> >>> a='kamotora.net' >>> a 'kamotora.net' >>> a[0] 'k' >>> a[1] 'a' >>> a[10] 'e' |
1 2 3 4 |
>>> a[15] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range |
1 2 3 4 5 6 |
>>> a[-1] 't' >>> a[-15] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range |
1 2 3 4 5 6 7 |
>>> a[0-1] 't' >>> a 'kamotora.net' >>> a[0-2] 'e' >>> |