LoginSignup
4
5

More than 5 years have passed since last update.

Pythonの基礎知識

Last updated at Posted at 2016-11-07

Pythonの基礎知識

スライスを利用した並び替え

例題00."stressed"の文字列を逆順に並び替える。

q00.py
#! usr/bin/pyenv python
# _*_ cording utf-8 _*_

word = "stressed"
print(word[::-1])
q00.pyの出力結果
desserts

Point
スライスを用いる。
スライスは、ある文字列の一部、または全部を抜き出すことができる。

word[(始点):(終点):(ステップ数)]

wordの始めから終わりまで全てを選択したい場合は、始点と終点は省略できる。

スライスを利用した抽出表示

例題01."パタトクカシーー"の文字列の奇数番目の文字を出力する。また、偶数番目の文字を出力する。

q01.py
#! usr/bin/pyenv python
# _*_ cording utf-8 _*_

word = "パタトクカシーー"

# 奇数番目の文字を抽出
extract1 = word[::2]
print(extract1)

# 偶数番目の文字を抽出
extract2 = word[1::2]
print(extract2)
q01.pyの出力結果
パトカー
タクシー

Point
 スライスを用いる場合には、文字列が確実に決まっている場合を除いて、始点や終点は省略するとよい。

zip関数を用いて、複数のオブジェクトを同時にループで処理

例題02."パトカー"と"タクシー"を先頭から交互に連結していき、"パタトクカシーー"を表示する。

q02.py
#! usr/bin/pyenv python
# _*_ cording utf-8 _*_

word1 = "パトカー"
word2 = "タクシー"
linking = ""

for (str1, str2) in zip(word1, word2):
    linking += (str1 + str2)
print(linking)
q02.pyの出力結果
パタトクカシーー

Point
 pythonでは、zip関数を用いることで複数のオブジェクトを同時にループで処理することができる。だが、複数のオブジェクトの場合、要素数が少ない方に実行回数が合わせられる。

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