简体   繁体   English

什么时候需要在 Python 中的 integer 周围添加引号

[英]When do I need to add quotation marks around an integer in Python

I just learnt that there is no quotation for integer in Python, but why is it needed in this case:刚刚得知Python中没有integer的报价,但是为什么在这种情况下需要它:

character_name = "Tom"
age = "50"
print("There once was a man named " + character_name + ",")
print("he was " + age + " years old.")

Using quotes to a digit, makes him become a string when it was an int (or float ) so it changes its values, you cannot do numerical operation on it anymore.对数字使用引号会使他在它是int (或float )时成为string ,因此它会更改其值,您不能再对其进行数字运算。

What you may need is the string representation of a number when concatenating it with other strings, here you may do您可能需要的是一个数字与其他字符串连接时的字符串表示形式,在这里您可以这样做

print("he was " + str(age) + " years old.")

Or, let print do it, by giving several parameters, and each one will be given its string representation或者,让 print 做到这一点,通过给出几个参数,每个参数都将被赋予它的字符串表示

print("he was", age, "years old.")

In resume, don't add quotes to a number when assigning it because it won't be a number anymore, handle it differently when you need but not as its beginning在简历中,分配数字时不要在数字中添加引号,因为它不再是数字,需要时以不同方式处理,但不要作为开头

You do not really need to do it if you use the format() method in Python 3, ie.:如果您使用 Python 3 中的format()方法,则实际上不需要这样做,即:

character_name = "Tom"
age = 50
print("There once was a man named {}, he was {} years old.".format(character_name), age)

This is better in case you need to use the variable age in some equation later in the code.如果您需要在代码后面的某个等式中使用变量age ,这会更好。

when you use 2 strings and a “+” you concate them but when you use 2 numbers and a “+” you summarize them so if you use one string and one number and a “+” it gives you an error so you convert your number to a string当你使用 2 个字符串和一个“+”时,你将它们连接起来,但是当你使用 2 个数字和一个“+”时,你会总结它们,所以如果你使用一个字符串和一个数字和一个“+”,它会给你一个错误,所以你转换你的数字到字符串

Valid Example 1: age = 30 name = “John” new_string = name + str(age)有效示例 1: age = 30 name = “John” new_string = name + str(age)

Valid Example 2: age = “30” name = “John” new_string = age + name有效示例 2: age = “30” name = “John” new_string = age + name

invalid Example: age = 30 name = “John” new_string = name + age #Throws an issue无效示例: age = 30 name = “John” new_string = name + age #Throws an issue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM