파이썬 변수 출력하기

Ddudduu·2023년 2월 28일
0

1. 기본 출력

입력

print('test')
print('test' + 'print')
print('test', 'print')

결과

test
testprint
test print

print() 로 출력하는 경우 + 는 띄어쓰기 없이 연결되지만 , 는 띄어쓰기 포함해서 연결된다!

2. 변수 출력

a. %d, %f

입력

a = 3
print('a is %d' %a)
    
b = 3.498
print('b is %f' %b)

결과

a is 3
b is 3.498000

정수를 출력할 땐 %d, 실수를 출력할 땐 %f 를 사용한다.

b. %s

입력

name = 'John'
print('My name is %s' %name)

결과

My name is John

변수를 출력할 때도 ,+ 로 연결해 출력할 수 있다.

입력

name = 'John'
print('My name is', name)
print('My name is' + name)

결과

My name is John
My name isJohn

, : 띄어쓰기 포함!
+ : 띄어쓰기 없이!

%s 를 여러개 사용할 수도 있다.

입력

firstName = 'John'
lastName = 'Lee'
print('first name is %s and last name is %s' %(firstName, lastName))

결과

first name is John and last name is Lee

%() 안에 출력할 변수를 차례대로 써준다.

c. format

format 명령어는 자료형을 고려하지 않아도 된다.
순서를 지정하는 것도 가능!

입력

firstName = 'John'
lastName = 'Lee'
print('first name is {} and last name is {}'.format(firstName,lastName))
print('last name is {1} and first name is {0}'.format(firstName,lastName))

결과

first name is John and last name is Lee
last name is Lee and first name is John
profile
Android

0개의 댓글