Python 2.6引入了该str.format()方法,其语法与现有%运算符略有不同.哪种情况更好,哪种情况更好?
以下使用每种方法并具有相同的结果,那么有什么区别?
#!/usr/bin/python
sub1 = "python string!"
sub2 = "an arg"
a = "i am a %s" % sub1
b = "i am a {0}".format(sub1)
c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)
print a # "i am a python string!"
print b # "i am a python string!"
print c # "with an arg!"
print d # "with an arg!"
Run Code Online (Sandbox Code Playgroud)此外,何时在Python中发生字符串格式化?例如,如果我的日志记录级别设置为HIGH,我仍然会执行以下%操作吗?如果是这样,有没有办法避免这种情况?
log.debug("some debug info: %s" % some_info)
Run Code Online (Sandbox Code Playgroud)在Python中,这种用于字符串格式化的习惯用法很常见
s = "hello, %s. Where is %s?" % ("John","Mary")
Run Code Online (Sandbox Code Playgroud)
Ruby中的等价物是什么?
在Python中,编写它是很繁琐的:
print "foo is" + bar + '.'
Run Code Online (Sandbox Code Playgroud)
我可以在Python中做这样的事吗?
print "foo is #{bar}."
ruby python language-comparisons string-formatting string-interpolation
[编辑00]:我已经多次编辑该帖子,现在甚至是标题,请阅读以下内容.
我只是了解了格式字符串的方法,其使用词典使用,如所提供的那些vars(),locals()和globals(),例如:
name = 'Ismael'
print 'My name is {name}.'.format(**vars())
Run Code Online (Sandbox Code Playgroud)
但是我想这样做:
name = 'Ismael'
print 'My name is {name}.' # Similar to ruby
Run Code Online (Sandbox Code Playgroud)
所以我想出了这个:
def mprint(string='', dictionary=globals()):
print string.format(**dictionary)
Run Code Online (Sandbox Code Playgroud)
您可以在此处与代码进行交互:http://labs.codecademy.com/BA0B/3#: workspace
最后,我想做的是将该函数放在另一个名为的文件中my_print.py,这样我就能做到:
from my_print import mprint
name= 'Ismael'
mprint('Hello! My name is {name}.')
Run Code Online (Sandbox Code Playgroud)
但就像现在一样,范围存在问题,我如何从导入的mprint函数中将主模块命名空间作为字典.(不是那个my_print.py)
我希望我自己理解,如果没有,尝试从另一个模块导入该功能.(回溯在链接中)
它正在访问globals()dict my_print.py,但当然变量名在该范围内没有定义,有关如何实现这一点的任何想法?
如果它在同一模块中定义,该函数可以工作,但请注意我必须如何使用,globals()因为如果不是,我只会得到一个mprint()范围内的值的字典.
我已经尝试使用非局部和点符号来访问主模块变量,但我仍然无法弄明白.
[编辑01]:我想我找到了一个解决方案:
在my_print.py中:
def mprint(string='',dictionary=None):
if dictionary is None:
import sys …Run Code Online (Sandbox Code Playgroud) 在 Python 中,我想创建一个带有嵌入式表达式的字符串块。
在 Ruby 中,代码如下所示:
def get_val
100
end
def testcode
s=<<EOS
This is a sample string that references a variable whose value is: #{get_val}
Incrementing the value: #{get_val + 1}
EOS
puts s
end
testcode
Run Code Online (Sandbox Code Playgroud) 提前警告!一名Python新手,还有一个非常糟糕的问题!
有没有一种速记方法:
"{} blabla ... {}".format(x, y)
Run Code Online (Sandbox Code Playgroud)
变成类似:
"{} blabla ... {}" % (x, y)
Run Code Online (Sandbox Code Playgroud)
使用运算符重载,例如语法还是其他?
不是在谈论旧式字符串格式,这种格式需要输入%s ...
我有一个未知数量的字符串%s,需要使用单个字符串进行格式化。
例如,如果我有一个字符串并想用它应该输出的"%s some %s words %s"单词对其进行格式化house"house some house words house"
执行以下操作会给我一个错误:
>>> "%s some %s words %s" % ("house")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
Run Code Online (Sandbox Code Playgroud)
因此,我决定执行以下操作,这可行,但对于这样一个简单的问题来说似乎过于复杂。
var = "house"
tup = (var,)
while True:
try:
print "%s some %s words %s" % tup
break
except:
tup += (var,)
Run Code Online (Sandbox Code Playgroud)
有没有更Pythonic的方法来做到这一点?
我正在尝试使用雪花连接器在表中插入一条记录。
在雪花文档中,他们展示了带有硬编码字符串的示例,但是当我尝试使用我的变量时,它不起作用。请建议在这种情况下如何使用变量。
conn.cursor().execute(
"INSERT INTO cm.crawling_metrics(FEED_DATE,COMP_NAME,REFRESH_TYPE,CRAWL_INPUT,CRAWL_SUCCESS) VALUES " +
"(score_creation_date,compName,sRefreshType,mp_sku_count,comp_sku_count)"
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Snowflake.connector.errors.ProgrammingError:000904(42000):SQL编译错误:位置100处的错误行1无效标识符“SCORE_CREATION_DATE”
注意:在上面的代码中,如果我用字符串而不是变量进行硬编码,它就可以工作。
请建议什么是正确的方法?