stay Python Middle splicing ( Connect ) Strings are very simple , You can write two strings next to each other , The specific format is :
strname = "str1" "str2"
strname Represents the string variable name after splicing ,str1 and str2 Is the string content to be spliced . Use this way of writing ,Python Will automatically splice two strings together .
str1 = "Python course " "http://c.biancheng.net/python/"
print(str1)
str2 = "Java" "Python" "C++" "PHP"
print(str2)
Python course http://c.biancheng.net/python/
JavaPythonC++PHP
It should be noted that , This method can only concatenate string constants .
If you need to use variables , You have to resort to + Operators , The specific format is :
strname = str1 + str2
Of course ,+ Operators can also concatenate string constants .
name = "C++ course "
url = "http://c.biancheng.net/cplus/"
info = name + " Our website is :" + url
print(info)
C++ The tutorial URL is :http://c.biancheng.net/cplus/
In many application scenarios , We need to put strings and numbers together , and Python Direct splicing of numbers and strings is not allowed , So we have to first convert numbers into strings . Can use str() and repr() Function to convert a number to a string , They are in the form of :
str(obj)
repr(obj)
obj Represents the object to be converted , It can be numbers 、 list 、 Tuples 、 Dictionaries and other types of data .
name = "C Chinese language network "
age = 8
course = 30
info = name + " already " + str(age) + " Year old , A total of " + repr(course) + " Set of tutorials ."
print(info)
C Chinese language network has 8 Year old , A total of 30 Set of tutorials .
str() and repr() Functions can convert numbers to strings , But there is a difference between them :
s = "http://c.biancheng.net/shell/"
s_str = str(s)
s_repr = repr(s)
print( type(s_str) )
print (s_str)
print( type(s_repr) )
print (s_repr)
<class ‘str’>
http://c.biancheng.net/shell/
<class ‘str’>
‘http://c.biancheng.net/shell/’
In this case ,s It's a string itself , But we still use str() and repr() It's converted . As you can see from the results ,str() It retains the original appearance of the string , and repr() Surround the string with quotation marks , This is it. Python The expression form of string .
in addition , stay Python Enter an expression in an interactive programming environment ( Variable 、 Add, subtract, multiply and divide 、 Logical operations, etc ) when ,Python Will be used automatically repr() Function handles the expression .