Python programming - string splicing

Author: Insist--

Personal homepage: insist--personal homepage

This article column: python column

Column introduction: This column is a free column, and will continue to update the basic knowledge of python . Welcome to subscribe and pay attention.

foreword

This article will explain the splicing of strings and the use of % for splicing.

Table of contents

​edit

1. String concatenation

2. Use% for splicing


1. String concatenation

Simply speaking, string concatenation is to splice two strings into one string to achieve a certain purpose. Splicing strings can be spliced ​​using the "+" sign. for example:

print("insist--"+"的文章")

#输出结果:insist--的文章

After watching the demo above, have you ever thought about a question? Obviously, two strings can be written into one string for output, why separate them and then splice them together? Therefore, string splicing is generally not used for splicing string literals, it is generally used for splicing between literals and variables or between variables and variables. for example:

#字面量和变量之间的拼接
a = "我是"
print(a + "insist--")

# 输出结果:我是insist--
#变量与变量之间进行拼接演示
a = "我是"
b = "真爱粉"
print(a + b)

#输出结果:我是真爱粉

2. Use% for splicing

After watching the demonstration of string concatenation, you may find it very convenient. The concatenation we demonstrated above only has two variables at most, so if there are hundreds of variables, do you still need to use the "+ sign" for concatenation? So string splicing has a disadvantage: it is too troublesome to splice when there are too many variables. So you can use string formatting for splicing.

As follows, we can use % for splicing, which is exactly placeholder splicing.

a = "insist--"
b = "%s的博客"%a
print(b)

#输出结果:insist--的博客

The % in the variable b indicates a placeholder, and s indicates that the variable is converted into a string and then placed in the placeholder.

Guess you like

Origin blog.csdn.net/m0_73995538/article/details/131748647