程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Explain seven ways to splice strings in Python

編輯:Python

Forget where to see a programming bull joking , He says programmers do two things a day , One of them is dealing with strings . I believe many students will feel the same way .

Almost any programming language , String is listed as the most basic and indispensable data type . And splicing strings is a necessary skill . today , I'll study with you Python Seven ways to concatenate strings .

1、 come from C Linguistic % The way

print('%s %s' % ('Hello', 'world'))
>>> Hello world
 Copy code 

% The way the number format strings is inherited from the old C Language , This has a similar implementation in many programming languages . In case of %s It's a place holder , It just represents a string , It's not the actual content of splicing . The actual splicing content is in a separate % Behind the number , Put it in a tuple .

Similar placeholders include :%d( Represents an integer )、%f( Represents a floating point number )、%x( Representing one 16 Hexadecimal number ), wait .% Placeholders are a feature of this kind of splicing , It's also a limitation , Because every placeholder has a specific meaning , It's too much trouble to use .

2、format() Splicing method

# Concise Edition
s1 = 'Hello {}! My name is {}.'.format('World', 'Python Programming learning circle ')
print(s1)
>>>Hello World! My name is Python Programming learning circle .
# Take the right number to the seat
s2 = 'Hello {0}! My name is {1}.'.format('World', 'Python Programming learning circle ')
s3 = 'Hello {name1}! My name is {name2}.'.format(name1='World', name2='Python Programming learning circle ')
print(s2)
>>>Hello World! My name is Python Programming learning circle .
print(s3)
>>>Hello World! My name is Python Programming learning circle .
 Copy code 

Use curly braces in this way {} Do a placeholder , stay format In the method, the actual splicing value . Easy to see , It's actually right % The improvement of No . In this way Python2.6 The introduction of .

In the above example , There is nothing in the curly brackets of the concise version , The disadvantage is that it's easy to get the order wrong . There are two main types of seating version , An incoming serial number , One uses key-value The way . In the actual combat , We recommend the latter , I can't count the wrong order , It's more intuitive and readable .

3、() Similar to tuple mode

s_tuple = ('Hello', ' ', 'world')
s_like_tuple = ('Hello' ' ' 'world')
print(s_tuple)
>>>('Hello', ' ', 'world')
print(s_like_tuple)
>>>Hello world
type(s_like_tuple) >>>str
 Copy code 

Be careful , In the above example s_like_tuple It's not a tuple , Because there is no comma separator between elements , These elements can be separated by spaces , You can also leave no spaces . Use type() see , To find it is a str type . I didn't find out why , Guess maybe () What's in brackets is being Python Optimized .

This way it looks fast , however , Brackets () The inner request element is a real string , You can't mix variables , So it's not flexible enough .

# When there are many elements , Variables are not supported
str_1 = 'Hello'
str_2 = (str_1 'world')
>>> SyntaxError: invalid syntax
str_3 = (str_1 str_1)
>>> SyntaxError: invalid syntax
# But there is no wrong way to write it
str_4 = (str_1)
 Copy code 

4、 Object oriented template splicing

from string import Template
s = Template('${s1} ${s2}!')
print(s.safe_substitute(s1='Hello',s2='world'))
>>> Hello world!
 Copy code 

Tell the truth , I don't like this way of realizing . A strong stink of being poisoned by object-oriented thinking .

Not much .

5、 frequently-used + Number mode

str_1 = 'Hello world! '
str_2 = 'My name is Python Programming learning circle .'
print(str_1 + str_2)
>>>Hello world! My name is Python Programming learning circle .
print(str_1)
>>>Hello world!
 Copy code 

This is the most common way 、 intuitive 、 Understandability , It's an entry-level implementation . however , It also has two things that make people prone to make mistakes .

First , Students who are new to programming are prone to make mistakes , They don't know that strings are immutable types , The new string will occupy a new block of memory , And the original string remains the same . In the above example , There are two strings before splicing , After splicing, there are actually three strings .

secondly , Some experienced programmers are also prone to make mistakes , They think when the number of splices does not exceed 3 when , Use + The number connector will be faster than any other way (ps: not a few Python The tutorials are all so recommended ), But there is no reasonable basis .

in fact , When splicing short literal values , because CPython Medium Constant folding (constant folding) function , These denominations will be converted into shorter forms , for example 'a'+'b'+'c' Converted to 'abc','hello'+'world' It will also be converted into 'hello world'. This conversion is done at compile time , At run time, there will be no more splicing operations , So it will speed up the overall calculation .

There is a limit to constant folding optimization , It requires that the length of the splicing result does not exceed 20. therefore , When the final string length of splicing does not exceed 20 when ,+ The way the number operator works , It's better than what I mentioned later join Wait a lot faster , This is related to + No matter how many times you use it .

6、join() Splicing method

str_list = ['Hello', 'world']
str_join1 = ' '.join(str_list)
str_join2 = '-'.join(str_list)
print(str_join1) >>>Hello world
print(str_join2) >>>Hello-world
 Copy code 

str The object has join() Method , Accept a sequence parameter , Can be spliced . When splicing , If the element is not a string , It needs to be changed first . It can be seen that , This method is more suitable for connecting sequence objects ( For example, a list of ) The elements of , And set a uniform space .

When the splicing length exceeds 20 when , This is basically the first choice . however , Its disadvantage is , It's not suitable for fragmented 、 Splicing of elements not in a sequence set .

7、f-string The way

name = 'world'
myname = 'Python Programming learning circle '
words = f'Hello {name}. My name is {myname}.'
print(words)
>>> Hello world. My name is Python Programming learning circle .
 Copy code 

f-string The way comes from PEP 498(Literal String Interpolation, Literal string interpolation ), from Python3.6 Version to introduce . Its characteristic is to add... Before the string f identification , Curly brackets are used in the middle of the string {} Package other string variables .

In this way, the readability of the second kill format() The way , When dealing with long string splicing , Speed vs join() The method is quite .

For all that , This is compared with some other programming languages , Still not elegant , Because it introduces a f identification . And some other programming languages can be simpler , such as shell:

name="world"
myname="Python Programming learning circle t"
words="Hello ${name}. My name is ${myname}."
echo $words
>>>Hello world. My name is Python Programming learning circle .
 Copy code 

To sum up , What we said earlier “ String splicing ”, In fact, it is understood from the result . If we divide it from the principle of implementation , We can divide these methods into three types :

Format class :%、format()、template
Splicing class :+、()、join()
Interpolation class :f-string

When dealing with sequence structures such as string lists , use join() The way ; The splicing length shall not exceed 20 when , choose + Sign operator mode ; The length exceeds 20 The situation of , High version selection f-string, The lower version depends on the situation format() or join() The way .

The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved