파이썬 & 오픈소스 개발 Tip과 강좌
이곳은 파이썬과 여러 오픈소스 기반 프레임워크 관련 Tip과 강좌 게시판 입니다. 관련 개발을 진행하면서 알아내신 Tip이나 강좌와 새로운 소식을 적어 주시면 다른 공부하는 분들에게 큰 도움이 됩니다. 감사합니다. SQLER.com은 개발자와 IT전문가의 지식 나눔을 실천하기 위해 노력하고 있습니다.
Python에서 random 문자열이나 숫자를 가져오는 방법 정리
Python random 문자열 생성
아래 문서에러 여러 방안들을 제공하고 있다. 잠시 알파벳,숫자 조합 랜덤 문자열이 필요할 경우 예를 들면 이런 패턴이다.
Python Generate Random String and Password (pynative.com)
import random import string # get random string of letters and digits source = string.ascii_letters + string.digits result_str = ''.join((random.choice(source) for i in range(8))) print(result_str) # Output vZkOkL97
그 외에도 password 스타일의 랜덤 보안 문자열 문자열 패턴을 제공하고 있다.
import secrets import string # secure random string secure_str = ''.join((secrets.choice(string.ascii_letters) for i in range(8))) print(secure_str) # Output QQkABLyK # secure password password = ''.join((secrets.choice(string.ascii_letters + string.digits + string.punctuation) for i in range(8))) print(password) # output 4x]>@;4)
Python random 숫자 생성
아래 문서에서 관련 내용을 볼 수 있다.
Python Random uniform() Method (w3schools.com)
import random print(random.uniform(20, 60))
이런 식으로, random.uniform을 이용하며 위의 코드는 20~60 사이의 float 수를 리턴한다.
만약 정수형 또는 특정 소수점 자리수 까지 리턴이 필요할 경우 round() 함수를 이용한다.
round 함수 : Python round() Function (w3schools.com)
참고링크:
Python Generate Random String and Password (pynative.com)
Python Random uniform() Method (w3schools.com)
Python round() Function (w3schools.com)