Pythonで文字列の一部、左から/右からn文字目を取り出す方法

paper IT

Pythonでは、リストと同じようにインデックスを指定して、文字列内のn文字目を取り出すことが可能です。

スポンサーリンク

文字抽出

文字列を用意します。
#python
文字列 = "abcde"
print(文字列[0])
print(文字列[1])
print(文字列[2])
この文字列に対し、インデックスを噛ませて出力すると、
1、2、3文字目が出力できるというわけです(インデックスは0から数えます)。
数字などの場合はエラーになるので、
str関数を噛ませて一度文字列に変更する必要があります。

右からn文字

#python
文字列 = "abcde"
print(文字列[-1])
print(文字列[-2])
print(文字列[-3])
Pythonではマイナスインデックスを使うことにより、右から数えてn文字目を取り出すことも可能です。
実行結果です。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny

モバイルバージョンを終了