I'm learning Python(3x) In the process of , There are some problems in splicing strings , So take a moment to sort it out Python Several ways to splice strings .
Using the plus sign to connect variables or elements must be of string type (<class ‘str’>)
for example :
str_name1 = 'To'
str_name2 = 'ny'
str_name = str_name1 + str_name2
print(str_name)
Output results :
print('-----------method2-----------')
# str.join(iterable)
# can join Conditions join(iterable) iterable Iterable , If the list (list) by Non nested list , The list element is a string (str) type ,
# Sequence type , Hash type Can be passed in as a parameter
# eg(1):
list_good_night = [' On the evening of ', ' On ', ' good ', '!']
str_night = ''.join(list_good_night)
print(str_night)
# eg(2):
# Splicing prefix (' Splicing prefix ').join(iterable)
str_night1 = '------>'.join(list_good_night)
print(str_night1)
# eg(3) Splicing iterable = Dictionaries key,value Required string Default splice key A list of
dict_name = {
'key1': 'value1', 'key2': 'value2'}
str_key = ','.join(dict_name)
# Splicing value A list of
str_value = ','.join(dict_name.values())
print(str_key)
print(str_value)
Execution results :
''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :153708845 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
# Use , One thing to note about the comma form , It can only be used for print Print , The assignment operation will generate tuples :
print('-----------method3-----------')
a, b = 'Hello', 'word'
c = a, b
print(a, b)
print(c)
print(type(c))
Output results :
print('-----------method4-----------')
print('hello''python')
# mehon5 Direct connection
print('-----------method5-----------')
print('hello''python')
# methon6 format Splicing str.format(args,**kwargs)
# eg(1) {} Act as a placeholder
str_word = 'hello, word! {} {}'.format(' Zhang San ', ' Li Si ')
print(str_word)
# eg(2) {[index]} Fill in by index position .format([0]=value1, [1]= value1},)
str_word_index0 = 'hell0, word!{0},{1}'.format(' Zhang San ', ' Li Si ')
str_word_index1 = 'hell0, word!{1},{0}'.format(' Zhang San ', ' Li Si ')
print(str_word_index0)
print(str_word_index1)
# eg(3) {[keyword]}
str_word_keyword = 'hell0, word!{a},{b}'.format(b=' Zhang San ', a=' Li Si ')
print(str_word_keyword)
# eg(4) {[keyword,indec]} keyword In the last
str_word1 = 'hell0, word!{1}{a}{0},{b}'.format('index0', 'index1', b=' Zhang San ', a=' Li Si ')
print(str_word1)
# eg(5) format The parameter type is unlimited , Be the ancestor of the Yuan Dynasty , list , aggregate , Dictionary output
str_word2 = 'hell0, word!{b}'.format(b=['eee', 'd'])
print(str_word2)
# eg(6) Use as a function
str_word3 = 'hello, word! {} {}'.format
word = str_word3(' Zhang San ', ' Li Si ')
print(word)
Output results :