Examples of raw string and Unicode string operators in Python

黄舟
Release: 2017-07-22 16:01:49
Original
1670 people have browsed it

这篇文章主要介绍了Python原始字符串与Unicode字符串操作符用法,结合实例形式分析了Python针对原始字符与Unicode字符的操作符用法,需要的朋友可以参考下

本文实例讲述了Python原始字符串与Unicode字符串操作符用法。分享给大家供大家参考,具体如下:


#coding=utf8
'''''
在原始字符串里,所有的字符串都是直接按照字面的意思来使用,
没有转义特殊或不能打印的字符。
正则表达式是一些告诫搜索匹配方式的字符串,
通过是由代表字符、分组、匹配信息、变量名、字符类等的特殊符号组成。
在原始字符串紧靠第一个引号前,需要加上r或R字母,来表示该字符是原始字符串。
原始字符串和普通字符串有这几乎完全相同的语法。
Unicode字符串操作符,大写的U和小写的u是在Python1.6中和Unicode字符串一起被引入的。
它用来把标准字符串或者包含Unicode字符的字符串转换成完全的Unicode字符串对象。
字符串方法和正则表达式引擎也支持Unicode。
Unicode操作符也可以接受原始Unicode字符串,只要将Unicode操作符和原始字符串操作符连接在一起。
注意:Unicode操作符必须出现在原始字符串操作符前面。
'''
import re
#原始操作符函数
def originalOper():
  #不是原始字符表示换行符
  print "\n"
  #是原始字符表示\n
  print r"\n"
  try:
    #对文件路径加r,不需要对\进行转义
    #文件路径中表示斜线
    testFile=open(r"E:\PythonDemo\CorePythonBook2\output","r")
    for line in testFile.readlines():
      #通过格式化字符串
      #优先使用repr()函数转换为原始字符
      line="%r" %line
      #对匹配模式进行加r处理
      #匹配的字符转换为原始字符
      m=re.search(r"\\[rn]",line)
      #字符串中是否包含匹配字符
      #如果包含输出该字符串
      if m is not None:
        print line
  except Exception,e:
    print e
  finally:
    testFile.close()
#Unicode操作符函数
def  unicodeOper():
  print u"abc"
  print u"\u1234"
  print u"abc\u1234\n"
  print ur"Hello\nWorld!"
#调用函数
#输出操作原始字符结果
originalOper()
#输出Unicode字符串
unicodeOper()
Copy after login

运行结果如下:

The above is the detailed content of Examples of raw string and Unicode string operators in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!