More on Modules and their Namespaces


Suppose you've got a module "binky.py" which contains a "def foo()". The fully qualified name of that foo function is "binky.foo". In this way, various Python modules can name their functions and variables whatever they
want, and the variable names won't conflict — module1.foo is different from module2.foo. In the Python vocabulary, we'd say that binky, module1, and module2 each have their own "namespaces," which as you can guess are variable name-to-object bindings.

For example, we have the standard "sys" module that contains some standard system facilities, like the argv list, and exit() function. With the statement "import sys" you can then access the definitions in the sys module
and make them available by their fully-qualified name, e.g. sys.exit(). (Yes, 'sys' has a namespace too!)

import sys

# Now can refer to sys.xxx facilities
sys.exit(0)

There is another import form that looks like this: "from sys import argv, exit". That makes argv and exit() available by their short names; however, we recommend the original form with the fully-qualified names because it's
a lot easier to determine where a function or attribute came from.


import sys

  # Now can refer to sys.xxx facilities
  sys.exit(0)

Online help, help(), and dir()

  • dir(sys) — dir() is
    like help() but just gives a quick list of its defined symbols, or "attributes"

The "print" operator prints out one or more python items followed by a newline (leave a trailing comma at the end of the items to inhibit the newline).
A "raw" string literal is prefixed by an 'r' and passes all the chars through without special treatment of backslashes, so r'x\nx' evaluates to
the length-4 string 'x\nx'. A 'u' prefix allows you to write a unicode string literal (Python has lots of other unicode support features -- see
the docs below).

raw = r'this\t\n and that'
print raw ## this\t\n and that multi = """It was the best of times.
It was the worst of times."""

String Methods

Here are some of the most common string methods:

  • s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
  • s.strip() -- returns a string with whitespace removed from the start and end
  • s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
    "s.isalpha()"discriminate the string s whether contains only alphas. example:1. s='dfd24s',s.isalpha() returns false; 2. s='sdufjd',s.isalpha() returns Ture.
  • s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
  • s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
  • s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
  • s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special
    case s.split() (with no arguments) splits on all whitespace chars.
  • s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

String Slices


  • s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
  • s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
  • s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way to copy a sequence like a string or list)
  • s[1:100] is 'ello' -- an index that is too big is truncated down to the string length

String %

Python has a printf()-like facility to put together a string. The % operator takes a printf-type format string on the left (%d int, %s string, %f/%g floating point), and the matching values in a tuple on the right (a tuple is made of values separated by commas,
typically grouped inside parentheses):

# % operator
text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

The above line is kind of long -- suppose you want to break it into separate lines. You cannot just split the line after the '%' as you might
in other languages, since by default Python treats each line as a separate statement (on the plus side, this is why we don't need to type semi-colons on each line). To fix this, enclose the whole expression in an outer set of parenthesis -- then the expression
is allowed to span multiple lines. This code-across-lines technique works with the various grouping constructs detailed below: ( ), [ ], { }.

# add parens to make the long-line work:
text = ("%d little pigs come out or I'll %s and %s and %s" %
(3, 'huff', 'puff', 'blow down'))

在python中是没有&&及||这两个运算符的,取而代之的是英文and和or

reference:

https://developers.google.com/edu/python/

Python学习笔记3-string的更多相关文章

  1. Python学习笔记:String类型所有方法汇总

    # 按字母表熟悉下string中的方法# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z# 标红的为常用重点的方法!! str = " ...

  2. python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹

    python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...

  3. Python学习笔记(十一)

    Python学习笔记(十一): 生成器,迭代器回顾 模块 作业-计算器 1. 生成器,迭代器回顾 1. 列表生成式:[x for x in range(10)] 2. 生成器 (generator o ...

  4. Python学习笔记(十)

    Python学习笔记(十): 装饰器的应用 列表生成式 生成器 迭代器 模块:time,random 1. 装饰器的应用-登陆练习 login_status = False # 定义登陆状态 def ...

  5. Python学习笔记,day5

    Python学习笔记,day5 一.time & datetime模块 import本质为将要导入的模块,先解释一遍 #_*_coding:utf-8_*_ __author__ = 'Ale ...

  6. python学习笔记目录

    人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...

  7. Python学习笔记_Python对象

    Python学习笔记_Python对象 Python对象 标准类型 其它内建类型 类型对象和type类型对象 Python的Null对象None 标准类型操作符 对象值的比較 对象身份比較 布尔类型 ...

  8. Python学习笔记之异常处理

    1.概念 Python 使用异常对象来表示异常状态,并在遇到错误时引发异常.异常对象未被捕获时,程序将终止并显示一条错误信息 >>> 1/0 # Traceback (most re ...

  9. Python学习笔记之类与对象

    这篇文章介绍有关 Python 类中一些常被大家忽略的知识点,帮助大家更全面的掌握 Python 中类的使用技巧 1.与类和对象相关的内置方法 issubclass(class, classinfo) ...

  10. Python学习笔记之函数

    这篇文章介绍有关 Python 函数中一些常被大家忽略的知识点,帮助大家更全面的掌握 Python 中函数的使用技巧 1.函数文档 给函数添加注释,可以在 def 语句后面添加独立字符串,这样的注释被 ...

随机推荐

  1. vc709时钟信号报单端信号错误的记录

    话说,为什么我又要跑去搞fpga玩了,不是应该招个有经验的开发人员么?大概是练度不够吧…… Xilinx这个板子阿,真鸡儿贵,我这还没啥基础,慢慢试吧: 看了乱七八糟各种文档先不提,我还是决定先控制L ...

  2. AtCoder Regular Contest 077 D - 11

    题目链接:http://arc077.contest.atcoder.jp/tasks/arc077_b Time limit : 2sec / Memory limit : 256MB Score ...

  3. hud1007 Quoit Design

    #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> # ...

  4. (2018干货系列十)最新android开发学习路线整合

    怎么学Android Android是一个以Linux为基础的半开源操作系统,主要用于移动设备,由Google和开放手持设备联盟开发与领导.据2011年初数据显示仅正式上市两年的操作系统Android ...

  5. javaweb笔记09—(session会话及验证码问题)

    第一部分+++++++++++1.session会话 定义:session会话——对某个web应用程序的一次整体访问的过程. 由来:无连接的http协议是无状态的,不能保存每个客户端私有信息 a用户和 ...

  6. Android之udp传输

    注意除了添加Internet权限外,还要添加两行代码 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDi ...

  7. ​DL_WITH_PY系统学习(第3章)

    本节提示: 1.DL的核心构建 2.Keras的简单介绍 3.搭建DL机器训练环境 4.使用DL模型解决基础问题 3.1 DL的基本构建:layer layer的定义:以1个或多个tensor作为输入 ...

  8. Codeforces 839A Arya and Bran

    Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going ...

  9. Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password

    Centos7.5 执行ansible命令报错 问题: [root@m01 ~]# ansible servers -a "hostname" -i ./hosts -u root ...

  10. ODAC(V9.5.15) 学习笔记(十二)TOraLoader

    名称 类型 说明 Columns TDAColumns 需要载入数据的每个字段定义 LoadMode TLoadMode 载入模式,包括: lmDirect 通过内部数据缓冲区载入到数据库中 lmDM ...