1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【python】文字列を逆順にする、回文かを判定する

Posted at

1.文字列を逆順にする

python.revers_string.py
def revers_string(string):return string[::-1]

これで逆になる。

スライス記法の負のステップを利用している。

スライス記法
[始端:終端:ステップ数]

一つ目の":"の両脇は、始端、終端を意味する。
始端、終端に何も指定しないと、文字列の最初から最後まで、という事になる。
(終端に-1を指定すると、文字列の末尾指定したりも出来る)

二つ目の":"の右側はステップを意味する。
負の数にすると、終端から始端へステップ分減っていく処理になる。

つまり、上記コードは引数に"あいうえお"と入力した際、
始端が0、終端が5となり、-1でステップするため、逆順処理となり、
"おえういあ"が戻り値となる。

2.文字列が回文か調べる

python.check_palindrome_string.py
def check_palindrome_string(string):return string==string[::-1]

1の文を利用して、文字列が回文かを調べる関数。
スライスって便利だね。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?