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. 【Alpha版本】冲刺阶段——Day3

    [Alpha版本]冲刺阶段--Day3 阅读目录 今日进展 问题困难 明日任务 今日贡献量 TODOlist [今日进展] 密码算法方面: 参考了md5/sha1+salt和Bcrypt后,我们决定使 ...

  2. xshell中出现的绿色背景的文件夹

    这种文件夹表示权限为777的文件夹 可以使用chmod 777 fileName进行权限修改 如果需要将文件夹以及其子文件夹的权限全部置为777 chmod 777 -R directoryName/ ...

  3. windows下cmd清屏命令cls

    windows下cmd清屏命令cls

  4. web前端利用leaflet生成粒子风场,类似windy

    wind.js如下: $(function() { var dixing = L.tileLayer.chinaProvider('Google.Satellite.Map', { maxZoom: ...

  5. linux系统电视盒子到底是什么

    经常看到各种大神说今天刷了什么linux系统可以干嘛干嘛了,刷了乌班图可以干嘛干嘛了,但是身为一个小白,对这种名词都是一知半解.所以这边给大家科普一下,什么是linux系统?电视盒子刷了这个可以干啥? ...

  6. Service_name 和Sid的区别

    Service_name:该参数是由oracle8i引进的.在8i以前,使用SID来表示标识数据库的一个实例,但是在Oracle的并行环境中,一个数据库对应多个实例,这样就需要多个网络服务名,设置繁琐 ...

  7. 计算概论(A)/基础编程练习(数据成分)/1:短信计费

    #include<stdio.h> int main() { // 输入当月发送短信的总次数n和每次短信的字数words int n,words; scanf("%d" ...

  8. django实现类似触发器的效果

    https://blog.csdn.net/pushiqiang/article/details/50652080?utm_source=blogxgwz1 https://blog.csdn.net ...

  9. Linux学习笔记之yum安装和卸载软件

    # yum -y install 包名(支持*) :自动选择y,全自动 # yum install 包名(支持*) :手动选择y or n # yum remove 包名(不支持*) # rpm -i ...

  10. P1288 取数游戏II

    luogu原题 最近刚学了博弈论,拿来练练手qwq 其实和数值的大小并没有关系 我们用N/P态来表示必胜/必败状态 先在草稿纸上探究硬币♦在最左侧(其实左右侧是等价的)的一条长链的N/P态,设链长为n ...