Ruby示例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
Run Code Online (Sandbox Code Playgroud)
成功的Python字符串连接对我来说似乎很冗长.
我需要找出如何将数字格式化为字符串.我的代码在这里:
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
Run Code Online (Sandbox Code Playgroud)
小时和分钟是整数,秒是浮点数.str()函数将所有这些数字转换为十分之一(0.1)的位置.因此,不是我的字符串输出"5:30:59.07 pm",它将显示类似"5.0:30.0:59.1 pm"的内容.
最重要的是,我需要为我做什么库/功能?
Python至少有六种格式化字符串的方法:
In [1]: world = "Earth"
# method 1a
In [2]: "Hello, %s" % world
Out[2]: 'Hello, Earth'
# method 1b
In [3]: "Hello, %(planet)s" % {"planet": world}
Out[3]: 'Hello, Earth'
# method 2a
In [4]: "Hello, {0}".format(world)
Out[4]: 'Hello, Earth'
# method 2b
In [5]: "Hello, {planet}".format(planet=world)
Out[5]: 'Hello, Earth'
# method 2c
In [6]: f"Hello, {world}"
Out[6]: 'Hello, Earth'
In [7]: from string import Template
# method 3
In [8]: Template("Hello, $planet").substitute(planet=world)
Out[8]: 'Hello, Earth'
Run Code Online (Sandbox Code Playgroud)
不同方法的简要历史:
printf自Pythons婴儿期以来,风格格式一直存在 …python printf string-formatting backwards-compatibility deprecated
我在python中编写spark代码.如何在spark.sql查询中传递变量?
q25 = 500
Q1 = spark.sql("SELECT col1 from table where col2>500 limit $q25 , 1")
Run Code Online (Sandbox Code Playgroud)
目前上面的代码不起作用?我们如何传递变量?
我也尝试过,
Q1 = spark.sql("SELECT col1 from table where col2>500 limit q25='{}' , 1".format(q25))
Run Code Online (Sandbox Code Playgroud) [编辑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)