Python 字符串

发布时间: 更新时间: 总字数:1701 阅读时间:4m 作者: 分享 复制网址

Python 字符串介绍

介绍

python 中字符串使用如下符号括的字符

  • 单引号 'abc',支持使用 \n \t 等输出
  • 双引号 "abc",支持使用 \n \t 等输出
  • 单个单引号 '''abc''',支持直接换行
  • 三个双引号 """abc""",支持直接换行
  • 在python3.0中,已经不再使用反引号 `

索引

s = 'ilovepython'

Python访问字符串的值:

  • 索引从左到右,默认0开始的,最大范围是字符串长度 -1
  • 索引从右到左,默认-1开始的,最大范围是字符串开头
  • 超出索引报错:IndexError: string index out of range

长度

len 用来计算字符串的长度

len(str)

注意:len在python中是一个内置函数,如果用来定义为变量长度,就会出错。

切片

切片格式:s[起始(包括):终止索引(不包括):步长]

s[0]    # i
s[1:5]  # love
s[-6:]  # python
s[::-1] # nohtypevoli
        # 等价于s[-1::-1]
        # step为负数,从左向右截取

字符串常见操作

  • 帮助:help(str)
  • s.isappha()
  • s.isdigit()

strip

s = ' xxx  AA'

# 剔除左右空格
s.strip()

# 剔除右空格
s.rstrip()

# 剔除左空格
s.lstrip()

# 剔除左右A
s.strip('A')

替换

s.replace('old', 'new')

开头、结尾判断

s = 'ilovepython'
print s.startswitch('ilo')  # True
print s.endswitch('ilo')    # True
'love' in s # True

计数

s.count('o')    # 2

查找索引

s.find('o')     # 6
s.index('o')    # 6

find vs index 区别:

In [1]: help("".index)
Help on built-in function index:

index(...)
    S.index(sub [,start [,end]]) -> int

    Like S.find() but raise ValueError when the substring is not found.


In [2]: help("".find)
Help on built-in function find:

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

分隔、拼接

"this is a    new string".split()
# ['this', 'is', 'a', 'new', 'string']

' '.join(['this', 'is', 'a', 'new', 'string'])
'this is a new string'

'*'.join(['this', 'is', 'a', 'new', 'string'])
'this*is*a*new*string'

说明:

  • 字符串也可以使用 + 拼接

特殊的字符串声名

  • 反斜杠转义:使用 反斜线(\) 对字符串中的引号进行转义
path="c:\\p\\s\\d"
  • 原始字符串以r开头,排除转义符号
print(r'c://python26')
  • Unicode字符串前加u
x = u'hello, world!'
type(x)
<type 'unicode'>

python2.x 由于历史原因,虽然支持unicode,但需要写成 u'xxx'python3.x 中是不需要。

格式化输出

f-string(推荐)

  • f-string 格式化字符串常量(formatted string literals),是 Python3.6 新引入的一种字符串格式化方法,来自 PEP 498 – Literal String Interpolation
  • f-string 在形式上是以 fF 修饰符引领的字符串(f'xxx'F'xxx'),以大括号 {} 标明被替换的字段
    • 输出大括号:{{}},示例:
  • f{t:width.precision}小数保留,整数 width 指定宽度,整数 precision 表示精度(保留小数点后几位小数)
    • f'{t*100:10.3f}'
>>> f"{{666}}{'abc'}"
'{666}abc'
>>> f"666{'{abc}'}"
'666{abc}'

简单示例

> name = 'Xianbin'
> f'Hello world, I'm {name}'
'Hello world, I'm Xianbin'

表达式求值与函数调用

> f'A total number of {24 * 8 + 4}'
'A total number of 196'

> name = 'XIANBIN'
> f'I'm {name.lower()}'
'I'm xianbin'

> import math
> f'The answer is {math.pi}'
'The answer is 1.1447298858494002'

引号、大括号与反斜杠

f-string 大括号内所用的引号不能和大括号外的引号定界符冲突,可根据情况灵活切换 '"'''"""

多行 f-string 拼接

> name = 'Xianbin'
> age = 26
> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Xianbin.I'm 26."

format() string(不推荐)

python2.6 开始,新增了一种格式化字符串的函数 str.format(),语法:

  • 通过 {}: 来代替 %

简单示例

>>> '{0},{1}'.format('xiexianbin.cn','welcom to you!')
'xiexianbin.cn,welcom to you!'
>>> '{},{}'.format('xiexianbin.cn','welcom to you!')
'xiexianbin.cn,welcom to you!'
>>> '{1},{0},{1}'.format('xiexianbin.cn','welcom to you!')
'welcom to you!,xiexianbin.cn,welcom to you!'
>>>

说明:字符串的format函数可以接受不限个参数,位置可以不按顺序,可以不用或者用多次,不过 python2.6 不能为空{}python 2.7才支持。

关键字设置

>>> '{domain},{word}'.format(domain='xiexianbin.cn', word='welcom to you!')
'xiexianbin.cn,welcom to you!'

对象设置

class Welcome:
    def __init__(self, domain, word):
        self.domain, self.word = domain, word

    def __str__(self):
        return "my domain is {self.domain}, {self.word}".format(self=self)

print Welcome("www.xiexianbin.cn", "welcome to you!")

输出为:

my domain is www.xiexianbin.cn, welcom to you!

下标设置

p = ["www.xiexianbin.cn", "welcome to you!"]
print '{0[0]}, {0[1]}'.format(p)

输出为:

www.xiexianbin.cn, welcome to you!

基本的python知识告诉我们,list和tuple可以通过“打散”成普通参数给函数,而dict可以打散成关键字参数给函数(通过和*),所以可以轻松的传个list/tuple/dict给format函数。非常灵活。

格式限定符

格式限定符 语法是{}中带:号

  • 填充与对齐

填充常跟对齐一起使用^、<、>分别是居中、左对齐、右对齐,后面带宽度:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充,如下:

print "{:>16}".format("123")
print "{:0>16}".format("123")
print "{:#>16}".format("123")

输出结果:

             123
0000000000000123
#############123
  • 精度与类型f

精度常跟类型f一起使用

print "{:.2f}".format(3.1415926)

输出结果:

3.14

其中.2表示长度为2的精度,f表示float类型。

  • 其他类型

主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。如下:

print "{:b}".format(18)
print "{:d}".format(18)
print "{:o}".format(18)
print "{:x}".format(18)

输出结果:

10010
18
22
12

号还能用来做金额的千位分隔符。如下:

print "{:,}".format(1234567890)

输出结果:

1,234,567,890

其他输出

使用 % 是古老版本 Python 的输出格式

"I'm from %s. %s is the capital of %s" % ("ZhengZhou", "ZhengZhou", "Henan")
# I'm from ZhengZhou. ZhengZhou is the capital of Henan
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数