Published 2021-11-24 09:56:10

Strings - 字符类型

字符串文本

字符串文本通常是由单引号或者双引号括起来的。通常单行单引号,多行三引号。

# Single quote
a = 'Yeah but no but yeah but...'
 
# Double quote
b = "computer says no"
 
# Triple quotes
c = '''
Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
not around the eyes,
don't look around the eyes,
look into my eyes, you're under.
'''

字符串转义

'\n'      # 换行
'\r'      # 回车
'\t'      # 水平制表符
'\''      # 单引号
'\"'      # 双引号
'\\'      # 反斜杠

字符串运算

+  # 字符串连接
*  # 重复
[] # 取子串
[:] # 截取字符串的一部分
in # 判断字符串是否包含某个字符串
not in # 判断字符串是否不包含某个字符串
r/re # 匹配字符串
% # 格式化字符串
 
 
a = "Hello"
b = "Python"
 
print "a + b 输出结果:", a + b
print "a * 2 输出结果:", a * 2
print "a[1] 输出结果:", a[1]
print "a[1:4] 输出结果:", a[1:4]
 
if( "H" in a) :
    print "H 在变量 a 中"
else :
    print "H 不在变量 a 中"
 
if( "M" not in a) :
    print "M 不在变量 a 中"
else :
    print "M 在变量 a 中"
 
print r'\n'
print R'\n'

字符串方法

s = ' Hello'
t = s.strip() #'Hello'去除空格
l = s.lower() #' hello' 全部转换为小写
u = s.upper() #' HELLO' 全部转换为大写
c = s.capitalize() #'Hello' 字符串首字母大写
t = s.replace('H', 'J') #'Jello' 将所有的H替换为J
 
s.endswith(suffix)     # 判断字符串是否以指定后缀结尾
s.find(t)              # 查找字符串中指定字符或字符串的索引位置
s.index(t)             # 查找字符串中指定字符或字符串的索引位置
s.isalpha()            # 判断字符串是否只有字母
s.isdigit()            # 判断字符串是否只有数字
s.islower()            # 判断字符串是否只有小写
s.isupper()            # 判断字符串是否只有大写
s.join(slist)          # 将字符串s与字符串列表slist中的字符串连接
s.lower()              # 转换字符串中所有大写字符为小写
s.replace(old,new)     # 替换字符串中的指定字符串
s.rfind(t)             # 从右边开始查找字符串中指定字符或字符串的索引位置
s.rindex(t)            # 从右边开始查找字符串中指定字符或字符串的索引位置
s.split([delim])       # 将字符串分割成一个列表
s.startswith(prefix)   # 判断字符串是否以指定前缀开头
s.strip()              # 去掉字符串左右两边的空格
s.upper()              # 转换字符串中的小写字母为大写

字符串类型转换

使用str()将任何值转换成字符串

x=42
str(x) #'42'

其他字符类型

# 字节类型
data = b'Hello World\r\n'
len(data)                         # 13
data[0:5]                         # b'Hello'
data.replace(b'Hello', b'Cruel')  # b'Cruel World\r\n'
 
# Raw字节类型
>>> rs = r'c:\newdata\test' # Raw (uninterpreted backslash)
>>> rs
'c:\\newdata\\test'
 
# f-string
>>> name = 'IBM'
>>> shares = 100
>>> price = 91.1
>>> a = f'{name:>10s} {shares:10d} {price:10.2f}'
>>> a
'       IBM        100      91.10'
>>> b = f'Cost = ${shares*price:0.2f}'
>>> b
'Cost = $9110.00'
>>>