파이썬에서 여러 인수를 인쇄하는 방법

Jinku Hu 2023년1월30일 Python Python Print
  1. 요구 사항
  2. 솔루션-파이썬에서 여러 인수 인쇄
  3. Python 3.6 전용 메소드-f- 문자열 형식
파이썬에서 여러 인수를 인쇄하는 방법

파이썬 2와 3에서 여러 인수를 인쇄하는 방법을 보여줍니다.

요구 사항

두 개의 변수가 있다고 가정

Python
 pythonCopycity = "Amsterdam"
country = "Netherlands"

다음과 같이 citycountry 인수를 모두 포함하는 문자열을 인쇄하십시오.

 blankCopyCity Amsterdam is in the country Netherlands

솔루션-파이썬에서 여러 인수 인쇄

파이썬 2와 3 솔루션

1. 값을 매개 변수로 전달

Python
 pythonCopy# Python 2
>>> print "City", city, 'is in the country', country

# Python 3
>>> print("City", city, 'is in the country', country)

2. 문자열 형식 사용

문자열에 인수를 전달할 수있는 세 가지 문자열 형식화 방법이 있습니다.

  • 순차적 옵션
Python
 pythonCopy# Python 2
>>> print "City {} is in the country {}".format(city, country)

# Python 3
>>> print("City {} is in the country {}".format(city, country))
  • 숫자 서식

    The advantages of this option compared to the last one is that you could reorder the arguments and reuse some arguments as many as possible. Check the examples below,

    Python
     pythonCopy# Python 2
    >> > print "City {1} is in the country {0}, yes, in {0}".format(country, city)
    
    # Python 3
    >> > print("City {1} is in the country {0}, yes, in {0}".format(country, city))
    
  • 명시 적 이름으로 형식화

Python
 pythonCopy# Python 2
>> > print "City {city} is in the country {country}".format(country=country, city=city)

# Python 3
>> > print("City {city} is in the country {country}".format(country=country, city=city))

3. 튜플로 인수를 전달

Python
 pythonCopy# Python 2
>>> print "City %s is in the country %s" %(city, country)

# Python 3
>>> print("City %s is in the country %s" %(city, country))

Python 3.6 전용 메소드-f- 문자열 형식

파이썬은 3.6 버전의 새로운 유형의 문자열 리터럴-f-strings을 소개합니다. 문자열 형식화 방법 인 str.format()과 비슷합니다.

Python
 pythonCopy# Only from Python 3.6
>>> print(f"City {city} is in the country {country}")
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - Python Print