本文已参与「新人创作礼」活动,一起开启掘金创作之路
字符串
使用不同的方式创建字符串
单引号和双引号创建字符串:
str1 = "python"
str2 = 'python'
print(str1)
print(str2)
输出:
python
三引号创建字符串:
str3 = """
我这个字符串太长了, 还要换个行。
"""
str4 = '''
我这个字符串太长了, 还要换个行。
'''
print(str3)
print(str4)
输出:
我这个字符串太长了,
还要换个行。
我这个字符串太长了,
还要换个行。
字符串的内置方法
```py S = "python" # 变量赋值
str.split(str="", num=-1):通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分 隔 num+1 个子字符串,-1 表示分割所有。
print(S.split('h')) # 输出[‘pyt’,’on’],根据 h 对字符串切割
str.replace(old, new[, max]):返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生 成的新字符串,如果指定第三个参数 max,则替换不超过 max 次。
print(S.replace('py','PY')) # Python,将字符串中的 py 替换为 PY
str.upper():返回小写字符转化为大写后的值。
print(S.upper())
PYTHON # str.lower():返回大写字符转化为小写后的值。
print('PYTHON'.lower()) # python,字符串转小写 line='aa,bb,ccc,dd\n' # \n 为换行
str.join(sequence):sequence:要连接的序列,返回指定字符连接序列中元素后生成的新字符串。
print(''.join(['life', 'is' ,'short'])) # 输出 life is short,join 拼接字符串 ```
查看字符串是否以某个字符开始或结束:
```py mystr = 'hello world,my name is python'
str.startswith(s):是否以 s 开始
print(mystr.startswith("hello"))
str. endswith(s):是否以 s 结束
print(mystr.endswith("world")) ```
删除字符串中开始和结尾的空格:
```py mystr = ' hello world,my name is python '
str.strip():删除两边的空格
print(mystr.strip()) ```
检查字符串中的数字和字母:
```py mystr = 'hello world,my name is python996' # str.isalpha:查看是否全是字母 print(mystr.isalpha())
str.isalpha:查看是否全是数字 print(mystr.isdigit())
str.isalnum:查看是否是字母和数字组成的
print(mystr.isalnum()) ```
格式化输出
```py
print('%f' % 1.11) # 默认保留 6 位小数 print('%.1f' % 1.11) # 取 1 位小数 print('%e' % 1.11) # 默认 6 位小数,用科学计数法 print('%.3e' % 1.11) # 取 3 位小数,用科学计数法 print('%20s' % 'hello world') # 右对齐,取 20 位,不够则补位 print('%-20s' % 'hello world') # 左对齐,取 20 位,不够则补位 print('%.2s' % 'hello world') # 取 2 位
```