小编phi*_*ndt的帖子

在每行的开头插入字符串

如何在文本文件中的每一行的开头插入一个字符串,我有以下代码:

f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
    for line in infile:
        f.insert(0, 'EDF ')
f.close
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

"'file'对象没有'insert'属性"

请注意,我是一个完整的编程n00b.

python string file

9
推荐指数
2
解决办法
1万
查看次数

添加int和str

你好,我正在读这本蟒蛇书,其中一个练习说:

编写一个名为right_justify的函数,该函数将名为s的字符串作为参数,并打印具有足够前导空格的字符串,以便字符串的最后一个字母位于显示的第70列.

好吧所以我有以下代码打印70个空格和字符串'allen'

def right_justify(s):
    print s
right_justify(' ' * 70 + 'Allen')
Run Code Online (Sandbox Code Playgroud)

但当我试图从字符串'Allen'中减去空格数

sub = len('allen')
def right_justify(s):
    print s
right_justify(' ' * 70 - sub + 'Allen')
Run Code Online (Sandbox Code Playgroud)

我得到:

" - str'和'int'的"不支持的操作数类型"

为什么没有子变量就可以工作呢?我检查了sub的类型,它以int形式出现.

python

1
推荐指数
2
解决办法
557
查看次数

帮助python代码

我正在阅读这本名为"Python for software design"的python书,它有以下练习:

假设一本书的封面价格是24.95美元,但书店可以获得40%的折扣.第一份副本的运费为3美元,每份额外的副本为75美分.60份的批发总成本是多少?

好的,我有以下代码:

bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60

bookDiscountAmount = bookPrice * discount * totalUnits
shipping = shippingPriceRest * 59 + shippingPriceFirst

result = bookDiscountAmount + shipping


print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(bookDiscountAmount)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
Run Code Online (Sandbox Code Playgroud)

有了这个,我得到以下结果:

  • 包括运费和折扣在内的60本书的总价格为: …

python

0
推荐指数
1
解决办法
6040
查看次数

标签 统计

python ×3

file ×1

string ×1