python中的数据类型的使用1

本文已参与「新人创作礼」活动,一起开启掘金创作之路

字符串

使用不同的方式创建字符串

单引号和双引号创建字符串:

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 位

```

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

宋小童

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

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

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

打赏作者

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

抵扣说明:

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

余额充值