LoginSignup
0
0

More than 1 year has passed since last update.

[Python]文字列/String

Last updated at Posted at 2021-09-26

概要

Pythonのtutorialで学んだ事を記します。

シングルクォート、ダブルクォート

Pythonで文字列を扱うにはシングルクォートかダブルクォートで囲む必要があります。

'Hello World' 又は "Hello World"

文字列と演算子

Pythonでは文字列と特定の演算子を組み合わせることもできます。

hello_world = "Hello" + "World"
print(hello_world)
# 結果
# HelloWorld

print(hello_world * 2)
# 結果
# HelloWorldHelloWorld

減算は出来ません

print("HelloWorldHelloWorld" - 1)
# 結果
# File "<stdin>", line 1, in <module>
# TypeError: unsupported operand type(s) for -: 'str' and 'int'

シングルクォートとダブルクォート、どちらが良い?

例えば下記のような文字列があったとする。

It's a string

この文字列をダブルクォートで囲んだ場合は、正常に機能する

my_string = "It's a string"
print(my_string)
# 結果
# "It's a string"

だが、シングルクォートで囲んだ場合はエラーとなる

my_string = 'It's a string'
print(my_string)
# 結果
# File "<stdin>", line 1
# mystring = 'It's a streing'
                   ^
# SyntaxError: invalid syntax

これは It'sのところでシングルクォートの囲みが終了してしまっているのが原因です。

これを解決する為には、エスケープシーケンスを使用することで解決できます。

my_string = 'It\'s a string'
print(my_string)
# 結果
# "It's a string"

ただ、エスケープシーケンスを乱用すると文字が読みにくくなるので、エスケープシーケンスを極力使用しない方法を選択するのがベストです。

今回の例でいくと、最初からダブルクォートで囲めばエスケープシーケンスは入りませんね。

"It's a string"

なので、その場面に応じたクォートを選択して使用したら良いと思います。

トリプルクォート

シングルとダブルの他にトリプルクォートがあります。

トリプルクォートは文字列を改行して記入することができます。

my_big_string = """This is line 1,
... this is line 2,
... this is line 3."""

print(my_big_string)
# 結果
# 'This is line 1,\n... this is line 2,\n... this is line 3.'

もっとも役に立つのがトリプルクォートはシングル、ダブルを中に記入することが出来る点です。

エスケープシーケンスが自動的に記入されていますね。

line = """He said: "Hello, I've got a question" from the audience"""

print(line)
# 結果
# 'He said: "Hello, I\'ve got a question" from the audience'

String Methods

Stringには文字列を操作する様々なメソッドがあります。

>>> my_string = "Hello world"
>>> my_string.
mystring.capitalize(    mystring.find(          mystring.isdecimal(     mystring.istitle(       mystring.partition(     mystring.rstrip(        mystring.translate(
mystring.casefold(      mystring.format(        mystring.isdigit(       mystring.isupper(       mystring.replace(       mystring.split(         mystring.upper(
mystring.center(        mystring.format_map(    mystring.isidentifier(  mystring.join(          mystring.rfind(         mystring.splitlines(    mystring.zfill(
mystring.count(         mystring.index(         mystring.islower(       mystring.ljust(         mystring.rindex(        mystring.startswith(
mystring.encode(        mystring.isalnum(       mystring.isnumeric(     mystring.lower(         mystring.rjust(         mystring.strip(
mystring.endswith(      mystring.isalpha(       mystring.isprintable(   mystring.lstrip(        mystring.rpartition(    mystring.swapcase(
mystring.expandtabs(    mystring.isascii(       mystring.isspace(       mystring.maketrans(     mystring.rsplit(        mystring.title(

例えば全ての文字を大文字にするならupperメソッド、小文字にするならlowerメソッドを使用できます。

my_string.upper()
# 'HELLO WORLD'

my_string.lower()
# 'hello world'

文字数を取得する

文字列の文字数を取得したいなら、len関数を使用することで取得できます。

空白も1文字として数えられるので、注意が必要です。

hello_world = 'Hello World'
len(hello_world)
# 結果
# 11
0
0
0

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