LoginSignup
5
6

More than 1 year has passed since last update.

Pythonでランダム文字列を生成する

Last updated at Posted at 2021-10-10

結論

こうするとできます。コメントアウトに出力を書いてます。

import random
s = ''.join(random.choices('PA', k=4))
print(s)
# PPAP

解説

random.choices('PA', k=4)P,A からランダムにどちらかを4回選んでリストに入れたものを作ります

import random
print(random.choices('PA', k=4))
# ['P', 'P', 'A', 'P']

''.join で文字列のリスト ['P', 'P', 'A', 'P'] を空文字で連結します

print(''.join(['P', 'P', 'A', 'P']))
# PPAP

以上

ちなみに

string.* が便利です。'PA' の代わりに使うと良いかもしれません。

import string
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_letters)   # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)          # 0123456789

random.choices は添字アクセス可能なオブジェクト(例: str, list)からランダムにk回選んでリストにしたものを返します
添字アクセス可能かどうかは以下のように判定できます

print(hasattr('PA', "__getitem__")) # True
print(hasattr(1, "__getitem__")) # False

__getitem__ は直接実行することもできます

print('PA'.__getitem__(0)) # => P
print('PA'.__getitem__(1)) # => A
print('PA'.__getitem__(2))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# IndexError: string index out of range

n = 1
print(n.__getitem__(0))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'int' object has no attribute '__getitem__'
print(n[0])
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not subscriptable

joinを使えば文字列のリストを改行で繋げることもできます。競プロでよく使ってます。

print('\n'.join(['P', 'P', 'A', 'P']))
# P
# P
# A
# P

参考

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