LoginSignup
0
1

More than 3 years have passed since last update.

【Python】メモ 関数について

Last updated at Posted at 2020-10-02

split 関数
数字、アルファベットや記号などが入り混じった文字列を切り分けてリスト化する

test = orange,apple,banana,strawberry
URL  = https://aaaa/bbbb/cccc/dddd

# test というリストを ” , ” で区切る 
#  ※多分使用している記号を指定するのだと思われる。
test.split(",") 
['orange', 'apple', 'banana', 'strawberry']

URL.split("/")
['https:', 'aaaa', 'bbbb', 'cccc', 'dddd']


# 引数に何も指定しない場合、スペースやタブ等で自動的に区切る
test.split()
['orange', 'apple', 'banana', 'strawberry']

input 関数
標準入力(用意されたデータ)を受け取るための関数

# 単発の場合
aaa = input()

# 複数行の場合
# ※改行してある入力データの場合は,下記のままだと \n が入っちゃうので注意
import sys
a = sys.stdin.readlines():

randrange 関数
range()の要素(下記ではリスト内)からランダムに要素を選出

import random
line = input().rstrip()
list = line.split(",")
# ["A", "B", "C"]

num = len(list)

# randrange(start, stop, step)と記載するらしいけど,start, stepは省略できる
print(list[random.randrange(num)])

translate, maketrans 関数
複数の文字を指定して置換する

t = str.translate(str.maketrans("ABCDEF", "123456"))
置換対象先をNoneに指定すると置換元が削除される

abs関数
絶対値に変換する

c = [-1, 3, -5]
a = abs(c)
print(a)

>>> [1, 3, 5]

map関数
文字列のリストを数値リストの変える関数

str_list = ["1", "-3", "-4.5"]
list = map(float, num_str_list)
print(list)

>>> [1.0, -0.3, -4.5]

count関数
特定の文字をカウントする

a = "hello world"
print(a.count("h"))

>>> 1

zfill関数
数値を右寄せゼロ埋めする

line = 7
total = line.zfill(3)
#()カッコ内の数値桁数文0埋めする
print(total)

>>> 007

随時学んだことを更新します。

0
1
1

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
1