Home >Backend Development >Python Tutorial >Introduction to three methods of Python string concatenation and formatted output

Introduction to three methods of Python string concatenation and formatted output

不言
不言Original
2018-09-19 17:32:373296browse

The content of this article is an introduction to three methods of formatted output of Python string splicing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The formatted output of string splicing is to edit the content that needs to be output, assign it to a variable, and finally output it to the screen.
Method 1

name = input('your name:')
age = int(input('your age:'))    # int() str转int。
job = input('your job:')

info = '''
---------- info of %s ---------    
Name : %s    
Age : %d
Job : %s
''' % (name,name,age,job)    # 此处 % 为连接符,把变量的值连接起来,顺序不能颠倒。

print(info)

Placeholder
%s s=string, universal, error-free, Python outputs a string by default.
%d d=digit, integer type.
%f f=float, decimal, 6 decimal places are saved by default. The value of the 6th decimal place is based on the 7th decimal place and will be rounded off.
%.3f, specify to save 3 decimal places.

Method Two

name = input('your name:')
age = int(input('your age:'))    # int() str转int。
job = input('your job:')

info = '''
---------- info of {_name} ---------
Name : {_name}
Age : {_age}
Job : {_job}
''' .format(_name=name,_age=age,_job=job)

print(info)

Method Three

name = input('your name:')
age = int(input('your age:'))    # int() str转int。
job = input('your job:')

info = '''
---------- info of {0} ---------
Name : {0}
Age : {1}
Job : {2}
''' .format(name,age,job)

print(info)

For string concatenation formatted output, it is recommended to use method 2 and method 3. There is also a plus sign connection method for splicing output, which is not recommended. Each additional plus sign will occupy some memory space and the execution efficiency is low.

The above is the detailed content of Introduction to three methods of Python string concatenation and formatted output. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn