python 字符串 String

1.python 字符串

首先,字符串是“不可变的”或只读的,创建后,字符串是不可修改的。

python 字符串由三种表达形式。

# Single quote
a = '你好'

# Double quote
b = "你好"

# Triple quotes
c = '''
你好,
世界。
'''

三引号通常捕获多行文本及所有格式。

单引号与双引号没有区别,但必须使用相同类型的引号,作为字符串起始和终止。

字符串转义码

'\n'      #换行
'\r'      #回车
'\t'      #Tab
'\''      #单引号
'\"'      #双引号
'\\'      #反斜杠

字符串索引

可以通过切片的方式访问字符串的字符。

a = 'Hello world'
b = a[0]          # 'H'
c = a[4]          # 'o'
d = a[-1]         # 'd' (end of string)

访问指定范围的字符串。

d = a[:5]     # 'Hello'
e = a[6:]     # 'world'
f = a[3:8]    # 'lo wo'
g = a[-5:]    # 'world'

字符串操作

# Concatenation (+)
a = 'Hello' + 'World'   # 'HelloWorld'
b = 'Say ' + a          # 'Say HelloWorld'

# Length (len)
s = 'Hello'
len(s)                  # 5

# Membership test (`in`, `not in`)
t = 'e' in s            # True
f = 'x' in s            # False
g = 'hi' not in s       # True

# Replication (s * n)
rep = s * 5             # 'HelloHelloHelloHelloHello'

字符串方法

常见字符串方法。

s.endswith(suffix)     # Check if string ends with suffix
s.find(t)              # First occurrence of t in s
s.index(t)             # First occurrence of t in s
s.isalpha()            # Check if characters are alphabetic
s.isdigit()            # Check if characters are numeric
s.islower()            # Check if characters are lower-case
s.isupper()            # Check if characters are upper-case
s.join(slist)          # Join a list of strings using s as delimiter
s.lower()              # Convert to lower case
s.replace(old,new)     # Replace text
s.rfind(t)             # Search for t from end of string
s.rindex(t)            # Search for t from end of string
s.split([delim])       # Split string into list of substrings
s.startswith(prefix)   # Check if string starts with prefix
s.strip()              # Strip leading/trailing space
s.upper()              # Convert to upper case

字符串转换

str()

原始字符串

原始字符串是带有未解释反斜杠的字符串文字。它们是通过在初始引号前加上小写“r”来指定的。

>>> rs = r'c:\newdata\test' # Raw (uninterpreted backslash)
>>> rs
'c:\\newdata\\test'

dir

获得当前模块的属性列表.

>>> s = 'hello'
>>> dir(s)
['__add__', '__class__', '__contains__', ..., 'find', 'format',
'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

2.字节串(Byte String)

通过在第一个引号之前放一个小 b,来指定它是一个字节字符串而不是文本字符串。

data = b'Hello World'

字节串的索引返回的是 ASCII 表中对应的整数。

data[0]   # 72 (ASCII code for 'H')

与文本字符串的转换。

text = data.decode('utf-8') # bytes -> text
data = text.encode('utf-8') # text -> bytes

3. 字符串输出

f-String

>>> a = f'{name:>10s} {shares:10d} {price:10.2f}'
>>> print(a) # 通常与print连用
'       IBM        100      91.10'
>>> b = f'Cost = ${shares*price:0.2f}'
>>> b

以上 {} 中的 s, d, f 为格式代码,类似于 C printf()。

常见格式代码:

d       Decimal integer
b       Binary integer
x       Hexadecimal integer
f       Float as [-]m.dddddd
e       Float as [-]m.dddddde+-xx
g       Float, but selective use of E notation
s       String
c       Character (from integer)

常用修饰符,调整字段宽度和小数精度。

:>10d   Integer right aligned in 10-character field
:<10d   Integer left aligned in 10-character field
:^10d   Integer centered in 10-character field
:0.2f   Float with 2 digit precision

字典格式输出。

format_map() 方法将字符串格式应用于字典:

>>> s = {
    'name': 'IBM',
    'shares': 100,
    'price': 91.1
}
>>> '{name:>10s} {shares:10d} {price:10.2f}'.format_map(s)
'       IBM        100      91.10'
>>>

f-strings 从提供的字典中获取值。

format() 格式

format()可以将格式应用于参数或关键字参数。

>>> '{name:>10s} {shares:10d} {price:10.2f}'.format(name='IBM', shares=100, price=91.1)
'       IBM        100      91.10'

更推荐使用 f- string的 方法。

C-Style 方法

C-Style 方法,可使用单个元素或元组作为参数值。

>>> 'The value is %d' % 3
'The value is 3'
>>> '%5d %-5d %10d' % (3,4,5)
'    3 4              5'

C-Style 方法是字节串唯一可用的输出格式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Not_Today.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值