[英]Python - What is the logic behind + function(i) +
In the following block of codes: 在以下代码块中:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
I understand that the code will run 5 times where i = 0 to 4. 我了解该代码将运行5次,其中i = 0到4。
However, I don't understand the logic behind the + operators added before and after the str() function. 但是,我不明白在str()函数之前和之后添加+运算符的逻辑。
How can this + function() + applied to other scenarios? +函数()+如何应用于其他场景?
str(i)
is the string representation of i
. str(i)
是的字符串表示i
。 Documentation : 说明文件 :
Return a str version of object.
返回对象的str版本。
If a
, b
and c
are strings, then a + b + c
is the string resulting of their concatenation. 如果
a
, b
和c
是字符串,则a + b + c
是它们的串联结果。
Therefore, with i
being an int
between 0
and 4
, say 3
, 'Jimmy Five Times (' + str(i) + ')'
is the folowing string: 因此,如果
i
是一个介于0
到4
之间的int
,比如说3
,则'Jimmy Five Times (' + str(i) + ')'
是以下字符串:
'Jimmy Five Times (3)'
In python, +
is used for string contate. 在python中,
+
用于字符串转换。 ie: 即:
data1 = "Hello"
data2 = "World"
print(data1+data2)
The output will be : 输出将是:
HelloWorld
str
is a function that returns a string representation of i
, so: str
是一个返回i
的字符串表示形式的函数,因此:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
# => 'Jimmy Fine Times (0)'
# => 'Jimmy Fine Times (1)'
# => 'Jimmy Fine Times (...
Calling a function that returns a string within a string concatenation 'A' + func() + 'B'
, will just use replace the function call with the string returned by the function (if no error or exceptions were raised), example: 调用返回字符串串联
'A' + func() + 'B'
的字符串的函数,将仅使用将函数调用替换为该函数返回的字符串(如果未引发错误或异常),例如:
def getName():
name=input('Enter name: ')
return name
print('Hello '+getName()+', Welcome to StackOverflow.')
#In: Enter name: Jack
#Out: Hello Jack, Welcome to StackOverflow.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.