python字符串转整数
Python supports string concatenation using + operator. In most of the programming languages, if we concatenate a string with an integer or any other primitive data types, the language takes care of converting them to string and then concatenate it. However, in Python, if you try to concatenate string and int using + operator, you will get a runtime error.
Python支持使用+运算符进行字符串连接。 在大多数编程语言中,如果我们将字符串与整数或任何其他原始数据类型连接在一起,则该语言会负责将它们转换为字符串,然后对其进行连接。 但是,在Python中,如果尝试使用+运算符将字符串和int连接起来,则会出现运行时错误。
Python连接字符串和整数 (Python Concatenate String and int)
Let’s look at a simple example to concatenate string and int using + operator.
让我们看一个使用+运算符将字符串和int连接起来的简单示例。
s = 'Year is '
y = 2018
print(s + y)
Output:
输出:
Traceback (most recent call last):
File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
print(s + y)
TypeError: can only concatenate str (not "int") to str
So how to concatenate string and int in Python? There are various other ways to perform this operation.
那么如何在Python中连接字符串和整数呢? 还有多种其他方式可以执行此操作。
使用str()函数 (Using str() function)
The easiest way is to convert int to a string using str() function.
最简单的方法是使用str()函数将int转换为字符串。
print(s + str(y))
Output: Year is 2018
产出: Year is 2018
使用%运算符 (Using % Operator)
print("%s%s" % (s, y))
使用format()函数 (Using format() function)
We can use string format() function too for concatenation of string and int.
我们也可以使用字符串format()函数来连接字符串和整数。
print("{}{}".format(s, y))
使用f弦 (Using f-strings)
If you are using Python 3.6 or higher versions, you can use f-strings too.
如果您使用的是Python 3.6或更高版本,则也可以使用f字符串 。
print(f'{s}{y}')
翻译自: https://www.journaldev.com/23642/python-concatenate-string-and-int
python字符串转整数