简体   繁体   English

普通字符串和以'%s'格式化的字符串有什么区别?

[英]What's the difference between a normal string and a string formatted by '%s'?

What's the difference between a normal string and a string formatted by '%s', because their results are different, like the following: 普通字符串和以'%s'格式化的字符串之间有什么区别,因为它们的结果不同,如下所示:

# It's ok
>>> "{%s}" % ' and '.join(['nice','good','perfect'])
'{nice and good and perfect}'

# It's not ok
>>> "{' and '}".join(['nice','good','perfect'])
"nice{' and '}good{' and '}perfect"

Your first example, 你的第一个例子

"{%s}"%' and '.join(['nice','good','perfect'])

joins the list with the given string, ' and ' then puts that in place of the %s 使用给定的字符串将列表加入' and '然后将其替换为%s

Your second example, 您的第二个例子

"{' and '}".join(['nice','good','perfect'])

joins the list with the given string, {' and '} . 用给定的字符串{' and '}加入列表。 So as you can see, these are two completely different operations, which is why you get a different output. 如您所见,这是两个完全不同的操作,这就是为什么您获得不同的输出的原因。

Change the code as 将代码更改为

"{" + " and ".join(['nice','good','perfect']) + "}"

Output: 输出:

'{nice and good and perfect}'

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

相关问题 python中的r'string'和普通的'string'有什么区别? - What's the difference between r'string' and normal 'string' in python? python在什么参数上区分格式化字符串和普通字符串? - On what parameter does python differentiate between a formatted string and a normal string? print和格式化的字符串文字之间有什么区别? - What is the difference between print and formatted string literals? Python 字符串格式中的 %s 和 %d 有什么区别? - What's the difference between %s and %d in Python string formatting? 在Python字符串格式中使用变量或%s有什么区别? - What's the difference between using a variable or %s in Python string formatting? 将字符串和字符串列表提供给 keras 标记器有什么区别? - What is the difference between giving a string and a list of string(s) to keras tokenizer? (在Python中)list(string).reverse()和list(string)[::-1]有什么区别? - (In Python) What's the difference between list(string).reverse() and list(string)[::-1]? Python中的字符串方法和str方法有什么区别? - what's the difference between string method and str method in Python? sqlalchemy 的数据类型中 Varchar 和 String 有什么区别? - What is the difference between Varchar and String in sqlalchemy's data type? Python列表理解和普通循环之间有什么区别? - What's the difference between Python list comprehension and normal loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM