资讯专栏INFORMATION COLUMN

[Learning Python] Chapter 7 String Fundamentals

baoxl / 573人阅读

摘要:此时不要在这里面的右边加入,否则会被当做。,这个式子可以将二进制数,转换为十进制的。需要注意的是,需要加上,表示。下面,表示括号内的第一个参数,表示第二个参数。

1, 字符串的连接concatenate有两种方式:
A:直接写在一起:

>>> title = "Meaning " "of" " Life" # Implicit concatenation
>>> title
"Meaning of Life"

B:使用+号

2,raw string: 在string前面加r,就会是string的不再具有转义功能。
应该注意的是,如果str的末尾是, Python仍然会将这个 和它后面的引号转义输出。这时候就不要用raw string了。

3,Triple quotes code multiline block strings: 三个引号(单引号或者双引号)可以做创造多行的strings。此时不要在这里面的右边加入comment,否则会被当做string。

4,triple quotes还可以用来暂时的是某段代码disable。如下面:

X = 1
"""
import os # Disable this code temporarily
print(os.getcwd())
"""
Y = 2

5,字符串可以进行切片操作,以截取某段字符:

>>> S = "spam"
>>> S[0], S[−2] # Indexing from front or end 进行index操作
("s", "a")
>>> S[1:3], S[1:], S[:−1] # Slicing: extract a section
("pa", "pam", "spa") # slice操作

6,切片的时候,包括写在左边的值,不包括写在右边的值。

7,三个参数的切片,X[I:J:K], 其中K表示步进step,如果不写K,则表示K位默认值+1.

8,步进可以是复数,这样的切片将得到倒着的字符串:

例子一:步进step = -1,获得倒序的字符串‘olleh’。

>>> S = "hello"
>>> S[::.1] # Reversing items
"olleh"    

例子二:这里仍然包括offset 5,不包括offset 1,该记住:切片包括写在左边的offset,不包括写在右边的offset。

>>> S = "abcedfg"
>>> S[5:1:−1] # Bounds roles differ
"fdec"

9,切片有时候可以用于截取文本中的某行字。通常来讲,每一行的结尾都是n,使用[:-1]即可以把n这个byte给去掉。虽然,人们更常用的是line.rstrip方法,因为有可能某行的行末未必有n.

10,ord()可以将某个字符转换为ASCII码,而chr则可以将ASCII码还原为所对应的字符。

11,int(‘1101’,2) 这个式子可以将二进制数1101,转换为十进制的integer。需要注意的是,1101需要加上‘’,2表示base。

12,string有个replace的方法,可以用来产生新的string。

>>> S = "splot"
>>> S = S.replace("pl", "pamal")
>>> S
"spamalot"

如果想要让Python只替换i次,需要填写它的第三个参数:

>>> S.replace("SPAM", "EGGS", 1) # Replace one
"xxxxEGGSxxxxSPAMxxxx"

13,虽然string是immutable sequence, 需要做in-place change的话还是可以先将string转换为list,在用’’.join(some_list)的方法生成一个新的string。

14,string有一个split方法,可以将string以某特定的分界符将string切细,并返回一个list。

例子一:split()里面没有参数,代表的是whitespce(空格, 制表位,换行等,数量不限)

>>> line = "aaa bbb ccc"
>>> cols = line.split()
>>> cols
["aaa", "bbb", "ccc"]

例子二:以逗号作为分界符,将string切细并返回一个list。

>>> line = "bob,hacker,40"
>>> line.split(",")
["bob", "hacker", "40"]

15,string的其他有用的方法:rstrip、upper、isalpha、endswith、startswith

16,格式化string有两种方法:
A: 类似于C语言的方法,String formatting expressions: "...%s..." % (values)
B: 从C#/.NET引进的方法:
String formatting method calls: "...{}...".format(values)

17, 针对方法A,下面的表格是格式的说明:

18,在%左边的格式是这样的:
%(keyname)widthtypecode
Keyname表示如果是dictionary的引用,这里写dictionary的key;
Flags: -号表示向左靠齐,0表示补零
Width 表示总共的位数
.precision 表示小数点右边要有多少位小数

19,下面的例子表示暂时不知道要有多少位小数,待传入值得时候确定:

>>> "%f, %.2f, %.*f" % (1/3.0, 1/3.0, 4, 1/3.0)
"0.333333, 0.33, 0.3333"  #这里最后选择了4位小数。

20,dictionary可以作为参数传入到这样的式子中:

>>> "%(qty)d more %(food)s" % {"qty": 1, "food": "spam"}
"1 more spam"

21,B方法:string format method 有如下4种基础类型:
Pass

22,更加复杂的如下面这种:

>>> somelist = list("SPAM")
>>> somelist
["S", "P", "A", "M"]
>>> "first={0[0]}, third={0[2]}".format(somelist)
"first=S, third=A"

23, A 方法使用 % 例子大全:

23.1 如果有两个参数,需要用括号将他们包围起来,括号前加%

>>> "That is %d %s bird!" % (1, "dead") # Format expression
That is 1 dead bird!

23.2 赋给一个variable代替%后面的内容

>>> exclamation = "Ni"
>>> "The knights who say %s!" % exclamation # String substitution
"The knights who say Ni!"

23.3 所有类型都可以使用%s,因为所有的object都可以转换为string。

>>> "%s -- %s -- %s" % (42, 3.14159, [1, 2, 3]) # All types match a %s target
"42 -- 3.14159 -- [1, 2, 3]"

23.4 –号表示向左靠齐。0表示用0补够数,6表示总共有6位

>>> x = 1234
>>> res = "integers: ...%d...%−6d...%06d" % (x, x, x)
>>> res
"integers: ...1234...1234 ...001234"

23.5 小数点后面的数字表示小数位数

>>> "%−6.2f | %05.2f | %+06.1f" % (x, x, x)
"1.23 | 01.23 | +001.2"

23.6 %配合字典dictionary使用

>>> "%(qty)d more %(food)s" % {"qty": 1, "food": "spam"}
"1 more spam"

23.7 字典配合使用

>>> reply = """
Greetings...
Hello %(name)s!
Your age is %(age)s
"""
>>> values = {"name": "Bob", "age": 40} # Build up values to substitute
>>> print(reply % values) # Perform substitutions
Greetings...
Hello Bob!
Your age is 40

23.8字典配合使用

>>> template = "%(motto)s, %(pork)s and %(food)s"
>>> template % dict(motto="spam", pork="ham", food="eggs")
"spam, ham and eggs"

24 B方法例子

24.1通过绝对位置

>>> template = "{0}, {1} and {2}" # By position
>>> template.format("spam", "ham", "eggs")
"spam, ham and eggs"

24.2 通过key,可以不用引号

>>> template = "{motto}, {pork} and {food}" # By keyword
>>> template.format(motto="spam", pork="ham", food="eggs")
"spam, ham and eggs"

24.3 混合

>>> template = "{motto}, {0} and {food}" # By both
>>> template.format("ham", motto="spam", food="eggs")
"spam, ham and eggs"

24.4 通过相对位置

>>> template = "{}, {} and {}" # By relative position
>>> template.format("spam", "ham", "eggs") # New in 3.1 and 2.7
"spam, ham and eggs"

24.5 字典,属性一起混合使用,下面的1表示format括号里的第2个参数,0表示字典里的第一个参数。

>>> import sys
>>> "My {1[kind]} runs {0.platform}".format(sys, {"kind": "laptop"})
"My laptop runs win32" 
>>> "My {map[kind]} runs {sys.platform}".format(sys=sys, map={"kind": "laptop"})
"My laptop runs win32"

24.6 下面,0表示format()括号内的第一个参数,1表示第二个参数。冒号后面是格式,>号表示向左靠齐,<表示向左靠齐,10表示的是总需要十位

>>> "{0:>10} = {1:<10}".format("spam", 123.4567)
" spam = 123.4567 "

24.7 如果冒号前面不写,则按照相对位置替换。

>>> "{:>10} = {:<10}".format("spam", 123.4567)
" spam = 123.4567 "

24.8 在格式的位置用e f g来约束

>>> "{0:e}, {1:.3e}, {2:g}".format(3.14159, 3.14159, 3.14159)
"3.141590e+00, 3.142e+00, 3.14159"
>>> "{0:f}, {1:.2f}, {2:06.2f}".format(3.14159, 3.14159, 3.14159)
"3.141590, 3.14, 003.14"

24.9 在格式的位置用x,o,b来约束,进而显示十六进制、八进制、二进制数

>>> "{0:X}, {1:o}, {2:b}".format(255, 255, 255) # Hex, octal, binary
"FF, 377, 11111111"

24.10 这里的1对应的是括号里的4,表示的是小数位数

>>> "{0:.{1}f}".format(1 / 3.0, 4) # Take value from arguments
"0.3333"

24.11 在d前面,或者e,f,g等前面加上逗号,可以每三个数用逗号隔开

>>> "{0:,d}".format(999999999999)
"999,999,999,999"

24.12 逗号要写在小数点的前面,如果他们都需要用到的话

>>> "{:,.2f}".format(296999.2567)
"296,999.26"

24.13 显示tuple

>>> "{0}".format((1.23,)) # Single value that is a tuple
"(1.23,)"

24.14 用关键字,对应于format里面的关键字

>>> "{num:d} = {title:s}".format(num=7, title="Strings")
"7 = Strings"

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/38327.html

相关文章

  • [Learning Python] Chapter 4. Introducing Python Ob

    摘要:可以连接,可以重复可以将两个连接在一起可以重复任意次数如中,号作用于表示连接,而作用于数字表示加法,操作符的作用会根据其作用的对象而有所适应。中的对象被分类为和。针对的核心类型,数字字符串和都是的。 1, >>> len(str(3)) 结果是1,len不能对数字求值,需要先将数字转换为str 2, math模块中,有许多工具可以用来计算数学问题。使用math模块,先导入math: i...

    CHENGKANG 评论0 收藏0
  • [Learning Python] Chapter 6: The Dynamic Typing In

    摘要:,可以对对象进行自动地回收。如下,这种情况的发生表示随改变了,应该意识到这个问题。代表引用相同则返回,否则,返回。这个判断会更加严格。的值为的两个量,其必定也是。,和指向了不同的。,由于会存储一些小的和小的以方便重新利用。 1, 在Python中,类型永远跟随object,而非variable。Variable没有类型。 2,在下面的三个式子中,a首先被赋予整形3,再被赋予字符串‘sp...

    lily_wang 评论0 收藏0
  • [Learning Python] Chapter 8 Lists and Dictionaries

    摘要:,如何一个方法一使用方法二使用方法方法三使用方法,按升序或降序排列表示升序表示降序和会返回。而仅能删除一个。使用方法可以避免这样的错误导致程序出现。,在中,的方法返回的不再是。不过可以使用强迫它们组成一个。 Chapter 8 Lists and Dictionaries1, list的concatenation 和 repetition 操作: >>> [1, 2, 3] + [4,...

    gekylin 评论0 收藏0
  • [Learning Python] Chapter 5 Numeric Types

    摘要:,可以用十进制十六进制八进制二进制来表示。由实数虚数组成。,在中,八进制可以以开头,但是在中,不能以开头,一定要以或者开头,位的运算表示位向左移动表示位向右移动表示或运算表示运算表示异或运算两者不同为,相同为可以用方法计算二进制数有多少位。 1, 在Python 2.x 中。Python的integer,有两种类型,normal和long。Normal通常是32位的。Long表示无限精...

    yuxue 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<