在python 2.7中划分字符串

时间:2017-06-03 20:20:21

标签: string python-2.7 math raspberry-pi configuration-files

我一直在制作一个自动百叶窗/窗帘项目已经有一段时间它一切运作良好,但我想在早上逐渐开启盲人的功能。我正在从配置文件中读取我的值,并已将值转换为可正常工作的字符串,但由于某种原因无法将该值除。我已经尝试了很多方法,但我似乎遇到了诸如以下错误: - SyntaxError:无法分配给运算符和TypeError:无法连接' str'和' int'对象。有没有人知道如何划分python字符串然后使用该字符串作为睡眠值?

我对编程很新(我13岁)

from ConfigParser import SafeConfigParser
config = SafeConfigParser()

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

## code to divide openTime by 5 and print the value

print 'gradual open time' + DividedOpenTime + ' seconds'

## code to repeat in a loop 5 times with a sleep of the value of 
## DividedOpenTime    

编辑1

嗨再次,我已经完成了我被告知要添加到代码中的内容,它已经解决了除法和睡眠时间的问题,但出于某种原因我无法打印这些值。第11行和第15行都有以下错误:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print 'gradual open time' + divOpenTime + ' this will repeat 5 times'
TypeError: cannot concatenate 'str' and 'float' objects

有谁知道如何解决这个问题?

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
import time

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

divOpenTime = float(openTime)/5 #working (:
loop = 0
print 'gradual open time' + divOpenTime + ' this will repeat 5 times'

for x in range(0, 5):
    loop += 1
    print 'gradual opening stage ' + loop + '/5'
    #GPIO true- I know how to do this
    time.sleep(divOpenTime) #working (:
    #GPIO False- I know how to do this
    time.sleep(15) #time between each interval fixed value

感谢Ed

2 个答案:

答案 0 :(得分:2)

您需要将字符串转换为数字以进行计算,

DividedOpenTime = float(openTime)/5

答案 1 :(得分:0)

我解决了

 print 'Gradual open time ' + str(divOpenTime) + ' seconds this will repeat 5 
 times'

您必须将浮点值添加/转换为字符串,以便打印。你做 这个:

str(Your_float_value_here)

再次感谢您的帮助Ed