Python基础

Python基础知识

#1.取绝对值
#2.取整

abs(-12.4)

round(21.6)
#16进制,前面加0x修饰,后面使用数字0-9A-F:
0xFF
#2进制,前面加0b修饰,后面使用数字0或1:
0b101010
#三引号用来输入包含多行文字的字符串:
s = """hello
world"""
print (s)
#字符串的分割:
s = "hello world"
s.split()
#s.split()将s按照空格(包括多个空格,制表符\t,换行符\n等)分割,并返回所有分割得到的字符串。
line = "1 2 3 4  5"
numbers = line.split()
print (numbers)
#s.split(sep)以给定的sep为分隔符对s进行分割。
line = "1,2,3,4,5"
numbers = line.split(',')
print (numbers)
#s.join(str_sequence)的作用是以s为连接符将字符串序列str_sequence中的元素连接起来,并返回连接后得到的新字符串:
s = ' '
s.join(numbers)
#s.replace(part1, part2)将字符串s中指定的部分part1替换成想要的部分part2,并返回新的字符串。
s = "hello world"
s.replace('world', 'python')
#s.upper()方法返回一个将s中的字母全部大写的新字符串。
"hello world".upper()
#s.lower()方法返回一个将s中的字母全部小写的新字符串。
s = "HELLO WORLD"
print (s.lower())
print (s)
#s.strip()返回一个将s两端的多余空格除去的新字符串。
s = "  hello world   "
s.strip()
#s.lstrip()返回一个将s开头的多余空格除去的新字符串。
#s.rstrip()返回一个将s结尾的多余空格除去的新字符串。
#可以使用dir函数查看所有可以使用的方法:
dir(s)
#当代码太长或者为了美观起见时,我们可以使用两种方法来将一行代码转为多行代码: ()  \
a = ("hello, world. "
    "it's a nice day. "
    "my name is xxx")
print(a)
a = "hello, world. " \
    "it's a nice day. " \
    "my name is xxx"
print(a)
#十六进制转换:
hex(255)
#八进制转换:
oct(255)
#二进制转换:
bin(255)
#还可以指定按照多少进制来进行转换,最后返回十进制表达的整数:
int('FF', 16)
int('11111111', 2)
#字符串中花括号 {} 的部分会被format传入的参数替代,传入的值可以是字符串,也可以是数字或者别的对象。
'{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue')
#可以用{<field name>:<format>}指定格式:
from math import pi
'{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * pi)
#也可以使用旧式的 % 方法进行格式化:
s = "some numbers:"
x = 1.34
y = 2
# 用百分号隔开,括号括起来
t = "%s %f, %d" % (s, x, y)
#包括索引 1 但是不包括索引 -2 。
s[1:-2]
#lower和upper可以省略,省略lower意味着从开头开始分片,省略upper意味着一直分片到结尾。
s[:3]
s[-3:]
#每隔两个取一个值:
s[::2]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值