当前位置:   article > 正文

Python字符串串联

python str 窜起来

String Concatenation is a very common operation in programming. Python String Concatenation can be done using various ways. This tutorial is aimed to explore different ways to concatenate strings in a python program.

字符串连接是编程中非常常见的操作。 Python字符串串联可以使用多种方式来完成。 本教程旨在探讨在python程序中连接字符串的不同方法。

Python字符串串联 (Python String Concatenation)

We can perform string concatenation using following ways:

我们可以使用以下方式执行字符串连接:

  • Using + operator

    使用+运算符
  • Using join() method

    使用join()方法
  • Using % operator

    使用%运算符
  • Using format() function

    使用format()函数
  • Using f-string (Literal String Interpolation)

    使用f字符串(文字字符串插值)

使用+运算符的字符串连接 (String Concatenation using + Operator)

This is the most simple way of string concatenation. Let’s look at a simple example.

这是最简单的字符串连接方式。 让我们看一个简单的例子。

  1. s1 = 'Apple'
  2. s2 = 'Pie'
  3. s3 = 'Sauce'
  4. s4 = s1 + s2 + s3
  5. print(s4)

Output: ApplePieSauce

输出: ApplePieSauce

Let’s look at another example where we will get two strings from user input and concatenate them.

让我们看另一个示例,我们将从用户输入中获取两个字符串并将它们连接起来。

  1. s1 = input('Please enter the first string:\n')
  2. s2 = input('Please enter the second string:\n')
  3. print('Concatenated String =', s1 + s2)

Output:

输出:

  1. Please enter the first string:
  2. Hello
  3. Please enter the second string:
  4. World
  5. Concatenated String = HelloWorld

It’s very easy to use + operator for string concatenation. However, the arguments must be a string.

使用+运算符进行字符串连接非常容易。 但是,参数必须是字符串。

  1. >>>'Hello' + 4
  2. Traceback (most recent call last):
  3. File "<input>", line 1, in
  4. TypeError: can only concatenate str (not "int") to str

We can use str() function to get the string representation of an object.

我们可以使用str()函数来获取对象的字符串表示形式。

Let’s see how to concatenate a string to integer or another object.

让我们看看如何将字符串连接为整数或另一个对象。

  1. print('Hello' + str(4))
  2. class Data:
  3. id = 0
  4. def __init__(self, i):
  5. self.id = i
  6. def __str__(self):
  7. return 'Data[' + str(self.id) + ']'
  8. print('Hello ' + str(Data(10)))
'
运行

Output:

输出:

  1. Hello4
  2. Hello Data[10]

The biggest issue with + operator is that we can’t add any separator or delimiter between strings. For example, if we have to concatenate “Hello” and “World” with a whitespace separator, we will have to write it as "Hello" + " " + "World".

+运算符的最大问题是我们不能在字符串之间添加任何分隔符或定界符。 例如,如果我们必须使用空格分隔符将“ Hello”和“ World”连接起来,则必须将其编写为"Hello" + " " + "World"

使用join()函数的字符串连接 (String concatenation using join() function)

We can use join() function to concatenate string with a separator. It’s useful when we have a sequence of strings, for example list or tuple of strings.

我们可以使用join()函数将字符串与分隔符连接起来。 当我们有一系列字符串时,例如列表或字符串元组 ,这很有用。

If you don’t want a separator, then use join() function with an empty string.

如果您不希望使用分隔符,请对空字符串使用join()函数。

  1. s1 = 'Hello'
  2. s2 = 'World'
  3. print('Concatenated String using join() =', "".join([s1, s2]))
  4. print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))

Output:

输出:

  1. Concatenated String using join() = HelloWorld
  2. Concatenated String using join() and spaces = Hello World

使用%运算符的字符串连接 (String Concatenation using % Operator)

We can use % operator for string formatting, it can be used for string concatenation too. It’s useful when we want to concatenate strings and perform simple formatting.

我们可以使用%运算符进行字符串格式化,也可以将其用于字符串连接。 当我们想要连接字符串并执行简单的格式化时,这很有用。

  1. s1 = 'Hello'
  2. s2 = 'World'
  3. s3 = "%s %s" % (s1, s2)
  4. print('String Concatenation using % Operator =', s3)
  5. s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018)
  6. print('String Concatenation using % Operator with Formatting =', s3)

Output:

输出:

  1. String Concatenation using % Operator = Hello World
  2. String Concatenation using % Operator with Formatting = Hello World from JournalDev - 2018

使用format()函数的字符串连接 (String Concatenation using format() function)

We can use string format() function for string concatenation and formatting too.

我们也可以使用string format()函数进行字符串连接和格式化。

  1. s1 = 'Hello'
  2. s2 = 'World'
  3. s3 = "{}-{}".format(s1, s2)
  4. print('String Concatenation using format() =', s3)
  5. s3 = "{in1} {in2}".format(in1=s1, in2=s2)
  6. print('String Concatenation using format() =', s3)

Output:

输出:

  1. String Concatenation using format() = Hello-World
  2. String Concatenation using format() = Hello World

Python String format() function is very powerful, using it just for concatenation of strings is not its proper use.

Python字符串format()函数非常强大,仅将其用于字符串连接是不合适的。

使用f字符串的字符串串联 (String Concatenation using f-string)

If you are using Python 3.6+, you can use f-string for string concatenation too. It’s a new way to format strings and introduced in PEP 498 – Literal String Interpolation.

如果您使用的是Python 3.6+,则也可以使用f-string进行字符串连接。 这是格式化字符串的新方法,并在PEP 498 –文字字符串插值中引入。

  1. s1 = 'Hello'
  2. s2 = 'World'
  3. s3 = f'{s1} {s2}'
  4. print('String Concatenation using f-string =', s3)
  5. name = 'Pankaj'
  6. age = 34
  7. d = Data(10)
  8. print(f'{name} age is {age} and d={d}')

Output:

输出:

  1. String Concatenation using f-string = Hello World
  2. Pankaj age is 34 and d=Data[10]

Python f-string is cleaner and easier to write when compared to format() function. It also calls str() function when an object argument is used as field replacement.

与format()函数相比,Python f字符串更干净,更易于编写。 当将对象参数用作字段替换时,它还会调用str()函数。

结论 (Conclusion)

Python String formatting can be done in several ways. Use them based on your requirements. If you have to concatenate sequence of strings with a delimited, then use join() function. If some formatting is also required with concatenation, then use format() function or f-string. Note that f-string can be used with Python 3.6 or above versions.

Python字符串格式可以通过多种方式完成。 根据您的要求使用它们。 如果必须用定界符连接字符串序列,请使用join()函数。 如果串联还需要某些格式,请使用format()函数或f字符串。 请注意,f-string可以与Python 3.6或更高版本一起使用。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/23575/python-string-concatenation

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号