随笔-121  评论-17  文章-0  trackbacks-0
  2009年8月18日

字符串是字符的序列。字符串基本上就是一组单词。


一. 如何在Python中使用字符串。

      (有时在带有‘\’的字符串里使用前缀r和R会无效,具体原因未知)

      (如果碰到异常:"EOL while scanning single-quoted string",一般是因为转义符的使用不当引起的)

Remark:

给C/C++程序员的注释
在Python中没有专门的char数据类型。确实没有需要有这个类型,我相信你不会为此而烦恼。


给Perl/PHP程序员的注释
记住,单引号和双引号字符串是完全相同的——它们没有在任何方面有不同。


给正则表达式用户的注释
一定要用自然字符串处理正则表达式。否则会需要使用很多的反斜杠。例如,后向引用符可以写成'//1'r'/1'

posted @ 2009-08-18 15:32 炜升 阅读(178) 评论(0) 编辑
在做python练习的时候,有个例子是直接使用zip命令去备份一个文件,我是用WINXP系统,中间发生了很多问题,log下来做backup.

例子程序是这样的:
#!/usr/bin/python
#
 Filename: backup_ver1.py

import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte''/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

# 3. The files are backed up into a zip file.
#
 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S'+ '.zip'

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    
print 'Successful backup to', target
else:
    
print 'Backup FAILED'

由于上面例子是在Unix/Linux下的,需要改成windows
#!/usr/bin/python
#
 Filename: backup_ver1.py

import os
import time

source 
=[r'C:\My Documents', r'D:\Work']
target_dir 
= r'F:\back up\'     # Remember to change this to what you will be using
target 
= target_dir + time.strftime('%Y%m%d%H%M%S'+ '.zip'
zip_command 
= "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    
print 'Successful backup to', target
else:
    
print 'Backup FAILED'

问题一:
当改好后,运行会发生异常,提示:"EOL while scanning single-quoted string",该异常出现在上面代码的粗体行
target_dir = r'F:\back up\'
发生错误主要是因为转义符与自然符号串间的问题,看Python的介绍: 如上所说, target_dir的值应该被视作 'F:\back up\',可是这里的转义符却被处理了。如果换成 r'F:\\back up\\' 转义符却没被处理,于是target_dir的值变为'F:\\back up\\'.将单引号变成双引号,结果还是如此。而如果给它加中括号【】,变成【r'F:\back up\'】,则程序又没问题...

于是,解决方法有2个:1)如上所说,加中括号;2)不使用前缀r,直接用转义符‘\’,定义变成target_dir = 'F:\\back up\\'.

问题二:
解决完问题一后,运行module,会提示backup fail. 检查如下:
1. 于是试着将source和target字符串打印出来检验是否文件路径出错,发现没问题
2. 怀疑是windows没有zip命令,在命令行里打‘zip’, 却出现提示帮助,证明可以用zip命令,而且有参数q,r;
3. 想起sqlplus里命令不接受空格符,于是试着将文件名换成没空格的, module成功运行...

现在问题换成如何能让zip命令接受带空格路径,google了一下,看到提示:“带有空格的通配符或文件名必须加上引号
于是对 zip_command稍做修改

     
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
改成:
     zip_command = "zip -qr \"%s\" \"%s\"" % (target, '\" \"'.join(source))

改后,module成功运行...

正确的script应为:
Code

posted @ 2009-08-18 15:15 炜升 阅读(278) 评论(2) 编辑