LoginSignup
4
7

More than 5 years have passed since last update.

pythonでの文字列の扱い

Last updated at Posted at 2018-10-10

 はじめに

pythonの基礎として、文字列の扱いについて記載します。

 環境

python3.6
anaconda1.8.2
macOS

 やってみる

  • シングルクォーテーション(一重引用符): '
  • ダブルクォーテーション(二重引用符): "
  • トリプルクォーテーション(三重引用符): ''', """

 シングルクォーテーションとダブルクォーテーション

>>> "hello"
'hello'

>>> 'hello'
'hello'

#同じ文字列だということがわかる
>>> a = "hello"
>>> b = 'hello'
>>> a == b
True

以下のコードは大丈夫

>>> "he said 'hello'" 
"he said 'hello'"

ダブルクォーテーションの中でダブルクォーテーションを使うとエラーがでる。

>>> "he said "hello""
  File "<stdin>", line 1
    "he said "hello""
                  ^
SyntaxError: invalid syntax

バックスラッシュ(winなら¥)でエスケープするとエラーが消える

>>> "he said \"hello\""
'he said "hello"'

さらに以下も同様にエラーが発生してしまう

>>> 'this isn't my apple'
  File "<stdin>", line 1
    'this isn't my apple'
              ^
SyntaxError: invalid syntax

同様にバックスラッシュ(winなら¥)でエスケープできる

>>> 'this isn\'t my apple'
"this isn't my apple"

print関数を使うと、クォーテーションを落として表示してくれる

>>> print('this isn\'t my apple')
this isn't my apple

もしそのままバックスラッシュ等を表示させたい場合はクォーテーション前にrをつける。

>>> print(r'this isn\'t my apple')
this isn\'t my apple

\nで改行ができる

>>> print("abc\ncde")
abc
cde

 トリプルクォーテーション

トリプルクォーテーションの場合は改行が反映される

>>> print('''abc
... cde
... efg
... ghi''')
abc
cde
efg
ghi

改行させない場合にはバックスラッシュを末尾につける

print('''abc\
... cde\
... efg\
... ghi''')
abccdeefgghi

 文字の連結と計算

文字列は「+」で連結でき、文字列同士は半角スペースで連結できる

>>> "hello"+"world"
'helloworld'

>>> "hello" "world"
'helloworld'

#「+」を使えば変数を使っていてもOK
>>> a = "hello"
>>> a + "world"
'helloworld'

#半角スペースはあくまでリテラル同士
>>> a "world"
  File "<stdin>", line 1
    a "world"
            ^
SyntaxError: invalid syntax

 インデックスの指定をして文字の取得

その前に文字数を取得

>>> word = "helloWorld"
>>> len(word)
10

インデックス指定

>>> word = "helloWorld"
>>> word[1]
'e'
>>> word[7]
'r'
>>> word[-3]
'r'
>>> word[0:5]
'hello'
>>> word[3:]
'loWorld'
>>> word[:3]+word[3:]
'helloWorld'

当然、文字数より大きいものをインデックス指定するとエラーが出ます。

>>> word[100]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[:100]
'helloWorld'

でもレンジとして指定する場合はエラーが出ません

>>> word[:100]
'helloWorld'

文字列は変更できません。

>>> word[:5]="goodmornig"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

変更ではなく、別に文字列を作成する必要があリます。

>>> "goodmornig"+word[5:]
'goodmornigWorld'

 おわり

4
7
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
4
7