编写helloworld.py文件
#!/usr/bin/python #coding=utf-8 print("hello world")
【注】在python2中要使用中文必须,添加#coding=utf-8,python3中可以不加
#单行注释
''' 多行注释 多行注释 '''
类型 | 符号 | 示例 |
---|---|---|
整形 | int | a=12 |
长整形 | long | b=10000000000 |
浮点型 | float | c=3.14 |
布尔类型 | True/False | |
字符串 | String | name="xiaoming" |
列表 | List | namesList = ['xiaoWang','xiaoZhang','xiaoHua'] |
元组 | Tuple | |
字典 | Dictionary |
【注】在python中定义一个变量,无需声明其类型,系统会自动辨别,可以使用type(a)来查看变量a的类型
>>> name = "xiaoming" >>> name 'xiaoming' >>> name[0] 'x' >>> name[1] 'i'
切片语法:[起始:结束:步⻓] 【注】 选取的区间属于左闭右开型
>>> name = "abcdefghijk" >>> name[0:3:1] 'abc' >>> name[1:9:2] 'bdfh' >>> name[1:9:1] 'bcdefghi' >>> name[1:9:-1] '' >>> name[::-1] 'kjihgfedcba' >>> name[2::] 'cdefghijk'
检测 str 是否包含在 mystr中, 如果是返回开始的索引值, 否则返回-1 语法:str.find(mystr,起始位置,结束位置) 或者 str.find(mystr)
>>> str = "you do not have to reboot to use the new driver." >>> mystr = "reboot" >>> str.find(mystr,0,len(str)) 19 >>> str.find(mystr) 19 >>> str.find("hello") -1
跟find()⽅法⼀样, 只不过如果str不在 mystr中会报⼀个异常.
>>> str = "you do not have to reboot to use the new driver." >>> mystr = "reboot" >>> str.index(mystr) 19 >>> str.index("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
返回 str在start和end之间 在 mystr⾥⾯出现的次数 mystr.count((mystr,起始位置,结束位置)
>>> str = "you do not have to reboot to use the new driver." >>> mystr = "reboot" >>> str.count(mystr) 1 >>> str.count(mystr,0,len(str)) 1
把 mystr 中的 str1 替换成 str2,如果 count 指定, 则替换不超过 count 次. mystr.replace(str1, str2, mystr.count(str1))
以 str 为分隔符切⽚ mystr, 如果 maxsplit有指定值, 则仅分隔 maxsplit 个⼦字符串 str.split(str=" ", 2)
>>> str 'you do not have to reboot to use the new driver.' >>> str.split("no") ['you do ', 't have to reboot to use the new driver.'] >>> str.split(" ") ['you', 'do', 'not', 'have', 'to', 'reboot', 'to', 'use', 'the', 'new', 'driver.'] >>> str.split(" ",2) ['you', 'do', 'not have to reboot to use the new driver.']
把字符串的第⼀个字符⼤写 mystr.capitalize()
>>> mystr = "hello world" >>> mystr.capitalize() 'Hello world'
把字符串的每个单词⾸字⺟⼤写
>>> mystr = "hello world" >>> mystr 'hello world' >>> mystr.title() 'Hello World'
检查字符串是否是以 obj 开头, 是则返回 True, 否则返回 False mystr.startswith(obj)
>>> mystr 'hello world' >>> mystr.startswith("h") True >>> mystr.startswith("obj") False
检查字符串是否以obj结束, 如果是返回True,否则返回 False. mystr.endswith(obj)
转换 mystr 中的⼩写字⺟为⼤写 mystr.upper()
>>> mystr 'hello world' >>> mystr.upper() 'HELLO WORLD'
转换 mystr 中所有⼤写字符为⼩写 mystr.lower()
>>> mystr ' HELLO WORLD' >>> mystr.lower() ' hello world'
删除 mystr 左边的空⽩字符 mystr.lstrip()
>>> mystr = " hello" >>> mystr ' hello' >>> mystr.lstrip() 'hello'
删除 mystr 字符串末尾的空⽩字符 mystr.rstrip()
同上
mystr 中每个字符后⾯插⼊str,构造出⼀个新的字符串 str.join(mystr)
str = " " >>> mystr = ["my","name","is","xiaoming"] >>> str.join(mystr) 'my name is xiaoming' >>>
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句