Python如何使用print()中的sep参数?示例

2021年4月2日11:32:38 发表评论 815 次浏览

Python中print()函数的参数之间的分隔符默认情况下是空格(软件空间功能), 它可以被修改, 并且可以根据我们的选择设置为任何字符, 整数或字符串。 " sep"参数用于实现相同的功能, 仅在python 3.x或更高版本中才能找到。它还用于格式化输出字符串。

例子:

#code for disabling the softspace feature
print ( 'G' , 'F' , 'G' , sep = '')
  
#for formatting a date
print ( '09' , '12' , '2016' , sep = '-' )
  
#another example
print ( 'pratik' , 'lsbin' , sep = '@' )

输出如下:

GFG
09-12-2016
pratik@lsbin

当sep参数与end参数一起使用时,它会产生令人惊叹的结果。结合sep和end参数的一些示例。

print ( 'G' , 'F' , sep = ' ', end=' ')
print ( 'G' )
#\n provides new line after printing the year
print ( '09' , '12' , sep = '-' , end = '\n' )
  
print ( 'prtk' , 'agarwal' , sep = ' ', end=' @')
print ( 'lsbin' )

输出如下:

GFG
09-12-2016
prtkagarwal@lsbin

注意:请在在线ide中将语言从Python更改为Python 3。

在cmd(Windows)或终端(linux)中键入python, 转到交互式python ide。

#import the below module and see what happens
import antigravity
#NOTE - it wont work on online ide

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: