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.
However, I don't understand the logic behind the + operators added before and after the str() function.
How can this + function() + applied to other scenarios?
str(i)
is the string representation of i
. Documentation :
Return a str version of object.
If a
, b
and c
are strings, then a + b + c
is the string resulting of their concatenation.
Therefore, with i
being an int
between 0
and 4
, say 3
, 'Jimmy Five Times (' + str(i) + ')'
is the folowing string:
'Jimmy Five Times (3)'
In python, +
is used for string contate. 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:
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:
def getName():
name=input('Enter name: ')
return name
print('Hello '+getName()+', Welcome to StackOverflow.')
#In: Enter name: Jack
#Out: Hello Jack, Welcome to StackOverflow.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.