What does end=' ' exactly do?
What does end=' ' exactly do?
So, I'm struggling trying to understand this kinda simple exercise
def a(n):
for i in range(n):
for j in range(n):
if i == 0 or i == n-1 or j == 0 or j == n-1:
print('*',end='')
else:
print(' ',end='')
print()
which prints an empty square. I tought I could use the code
print("*", ''*(n-2),"*")
to print the units in between the upper and the lower side of the square but they won't be aligned to the upper/lower side ones, which doesn't happen if you run the first code... so... could this be because of end=''
or print()
(would you be so kind and tell me what do they mean?)?
回答1
Check the reference page of print
. By default there is a newline character appended to the item being printed (end='\n'
), and end=''
is used to make it printed on the same line.
And print()
prints an empty newline, which is necessary to keep on printing on the next line.
EDITED: added an example.
Actually you could also use this:
def a(n):
print('*' * n)
for i in range(n - 2):
print('*' + ' ' * (n - 2) + '*')
if n > 1:
print('*' * n)
回答2
In Python 3.x, the end=' ' is used to place a space after the displayed string instead of a newline.
please refer this for a further explanation.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-09-17 向量内积(点乘)和外积(叉乘)概念及几何意义
2021-09-17 jQuery Migrate
2021-09-17 Best way to expose resource strings to JavaScript files in ASP.NET MVC?
2021-09-17 What's the difference between sweetalert and sweetalert2?
2021-09-17 Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]
2021-09-17 sweetalert2 and xss
2021-09-17 上海居住证办理条件以及流程?