Pep 3101提供了最终用%该format方法替换操作员的基本原理.这个问题和接受的答案都在同一点上.
但是,我找不到新语法的基本原理,我不明白这种改变的好处.pep 3101列出了各种替代语法,其中还包括printfC99标准及其变体中所述的着名格式说明符.(对于文档例如去这里第7.19.6.1的页数"fprintf函数" 274ff).
对于新string.format()方法,它被认为重用了%运营商使用的相同格式规范语言.
使用旧语法无法完成的新语法可以做些什么?
编辑:参数重新排序也可以像添加到ANSI C标准一样添加到旧语法中.最近看到了man sprintf
我想按顺序获取文件名列表.就像是
files-1-loop-21
files-1-loop-22
files-1-loop-23
files-1-loop-24
files-2-loop-21
files-2-loop-22
files-2-loop-23
.
.
.
and so on
Run Code Online (Sandbox Code Playgroud)
至于测试,我编写了如下python代码:
代码sample_1:
for md in range(1,5):
for pico in range(21,25):
print md, pico
Run Code Online (Sandbox Code Playgroud)
它给了我一对数字,如:
`1 21
1 22
1 23
1 24
2 21
2 22
2 23
2 24
3 21
3 22
3 23
3 24
4 21
4 22
4 23
4 24
Run Code Online (Sandbox Code Playgroud)
`
如果我使用:
代码sample_2:
for md in range(1,5):
for pico in range(21,25):
print "file-md-loop-pico"
Run Code Online (Sandbox Code Playgroud)
我明白了
files-md-loop-pico
files-md-loop-pico
files-md-loop-pico
files-md-loop-pico
files-md-loop-pico
files-md-loop-pico …Run Code Online (Sandbox Code Playgroud) 我正在尝试strip()使用正则表达式重新创建python的功能。这是Automate the Boring Stuff with Python的最后一个练习题。这是我的代码:
import re
stripChar = input('Enter character to strip: ')
context = input('Enter string to strip: ')
stripContext = None
def strip(char, string):
if stripChar == "":
regsp = re.compile(r'^\s+|\s+$')
stripContext = regsp.sub("", context)
return stripContext
else:
stripContext = re.sub(r'^(char)+', "", string)
return stripContext
print(strip(stripChar, context))
Run Code Online (Sandbox Code Playgroud)
在第 16 行,如果我用任何随机字符替换 (char),则程序正在运行。但是,我似乎无法在那里创建自定义变量。我在那里做错了什么?
编辑:堆栈说它是这个问题的重复。这不是因为它纯粹是围绕 Regex 而不仅仅是 Python。
我希望文本是一个键:每行计数。现在它将文件保存为普通字典,我无法弄清楚。
def makeFile(textSorted, newFile) :
dictionary = {}
counts = {}
for word in textSorted :
dictionary[word] = counts
counts[word] = counts.get(word, 0) + 1
# Save it to a file
with open(newFile, "w") as file :
file.write(str(counts))
file.close()
return counts
Run Code Online (Sandbox Code Playgroud) %当python不是模数或字符串格式化时,符号在python中意味着什么?我在timeit模块中这个令人困惑的代码块中遇到了它:
# Don't change the indentation of the template; the reindent() calls
# in Timer.__init__() depend on setup being indented 4 spaces and stmt
# being indented 8 spaces.
template = """
def inner(_it, _timer):
%(setup)s
_t0 = _timer()
for _i in _it:
%(stmt)s
_t1 = _timer()
return _t1 - _t0
"""
def reindent(src, indent):
"""Helper to reindent a multi-line statement."""
return src.replace("\n", "\n" + " "*indent)
Run Code Online (Sandbox Code Playgroud)
我搜索谷歌和SO这个运营商是什么,但没有运气.我使用的是python 2.6.1.
困惑的新手在这里.使用之间有什么区别:
print ("So you are {0} years old".format(age))
Run Code Online (Sandbox Code Playgroud)
和
print ("So you are", age, "years old")
Run Code Online (Sandbox Code Playgroud)
两者都有效.
现在,我想将数组转换为这样的字典:
dict = {'item0': arr[0], 'item1': arr[1], 'item2': arr[2]...}
Run Code Online (Sandbox Code Playgroud)
如何在python中优雅地解决这个问题?
我意识到这个问题可以被解释为与其他问题类似,所以在我开始之前,这里列出了一些可能的"重复",然后每个人都开始指出它们.这些似乎都不能正确回答我的问题.
我的问题特别适用于使用string.format()方法显示整数.
在运行python 2.7的解释器中使用%字符串格式运行以下代码
>>> print "%d" %(1.2345)
1
Run Code Online (Sandbox Code Playgroud)
而使用string.format()方法会产生以下结果
>>> print "{:d}".format(1.2345)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object type 'float'
Run Code Online (Sandbox Code Playgroud)
我期待两者都有同样的行为; 解释器在显示之前实际将我的浮点数转换为整数.我意识到我可以使用int函数将浮点数转换为整数格式,但我正在寻找与%d格式化方法相同的功能.是否有任何string.format()方法可以帮我吗?
假设我已经声明了三个变量,它们是一个日期,我如何将它们组合成一个新的变量,我可以通过简单地打印新的变量名称以正确的1/2/03格式打印它们.
month = 1
day = 2
year = 03
date = month, day, year <<<<< What would this code have to be?
print(date)
Run Code Online (Sandbox Code Playgroud)
我知道如果我单独调用所有三个变量,我可以在print语句中设置sep ='/'参数,但这意味着我不能在print语句中添加另外的文本而不用/分隔.因此我需要一个我可以调用的变量.
我在定义中使用Python的字符串格式化方法来调用一些.txt文件.一个这样的例子是:
def call_files(zcos1,zcos1,sig0):
a,b = np.loadtxt('/home/xi_'+str(zcos1)+'<zphot'+str(sig0)+'<'+str(zcos2)+'_.dat',unpack=True)
Run Code Online (Sandbox Code Playgroud)
这里str(sig0)给出了调用的地方sig0 == 0.050.然而,当我这样做,而不是采取0.050,它是四舍五入0.05!
我如何str(sig0)成为0.050代替0.05?
python ×10
string ×3
python-3.x ×2
dictionary ×1
formatting ×1
function ×1
numpy ×1
regex ×1
variables ×1