- 1.python 字符串
- 字符串转义码
- 字符串索引
- 字符串操作
- 字符串方法
- 字符串转换
- 原始字符串
- f-String
- dir
- 2.字节串(Byte String)
首先,字符串是“不可变的”或只读的,创建后,字符串是不可修改的。
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:newdatatest' # Raw (uninterpreted backslash) >>> rs 'c:\newdata\test'f-String
>>> a = f'{name:>10s} {shares:10d} {price:10.2f}'
>>> a
' IBM 100 91.10'
>>> b = f'Cost = ${shares*price:0.2f}'
>>> b
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



