python第二章

python第二章

string(字符串)

何为字符串

字符串是以单引号或者双引号括起来的任意文本,比如’This is an apple.'或者"This is an apple."。但是要注意引号本身是一种表现形式,不属于字符串的一部分。

​ 注意:如果字符串本身带双引号 ‘This is an “apple“.’

创建字符串

str1 = 'This is an apple.'
str2 = "This is a banana."

字符串运算

# 字符串拼接
str3 = 'This is an apple.'
str4 = "This is a banana."
print(str3 + str4)
#重复输出字符串
print(str3 * 3)
# 通过索引下标获取字符串中的字符,索引从0开始(程序员放羊)   str[index]
print(str3[6])
# 截取字符串中的一部分  切片编程
print("*"+str3[5:11]+"*")
print("*"+str3[5:]+"*")
print("*"+str3[:12]+"*")
# 判断字符串中是否存在某些内容
print("natasha" in str3)
print("apple" in str3)

运行结果:

This is an apple.This is a banana.
This is an apple.This is an apple.This is an apple.
s
*is an *
*is an apple.*
*This is an a*
False
True

格式化输出(占位符)

%s 格式化字符串

%d 格式化整数

%f 格式化浮点数,可以指定小数点后的精度,默认保留小数点后6位

name = "natasha"
age = 20
height = 177
'''
需要的效果:
natasha is a good man, he is 20 years old, his height is 177cm.
'''
print(name, "is a good man, he is", age, "years old, his height is", height, "cm.")
#如果只有一个替换,可以不写%后面的小括号,但是建议还是不要省略
print("%s is a good man, he is %d years old, his height is %.2fcm."%(name, age, height))
weight=75
print("*%d*"%(weight))
print("*%5d*"%(weight))
print("*%-5d*"%(weight))
print("*%.5d*"%(weight))

运行结果:

natasha is a good man, he is 20 years old, his height is 177 cm.
natasha is a good man, he is 20 years old, his height is 177.00cm.
*75*
*   75*
*75   *
*00075*

常用转义字符

反斜杠 \\

单引号 \'

双引号 \"

换行 \n

横向制表符 \t

str5 = '\\'
print(str5)
str6 = "This is \"an\" apple."
print(str6)
print("This is \nan apple.")
# 如果字符串内部有过个换行,用\n写在一行里非常利于阅读
print("This\nis\nan\napple.")
print('''
This
is
an
apple
''')
print("apple\tbanana")
# 如果字符串里面有很多字符需要转义,就需要加入很多\,为了简化,python允许使用r''表示''内部的字符串默认不转义
print('\\\t\\')
print(r'\\\t\\')

运行结果:

\
This is "an" apple.
This is 
an apple.
This
is
an
apple.

This
is
an
apple

apple	banana
\	\
\\\t\\

string的内置函数

eval()

'''
原型:eval(*args, **kwargs)
功能:将字符串当成有效的表达式来求值并返回计算结果
参数:
'''
num1 = eval("123")
print(num1)
print(type(num1))
print(eval("+123"))
print(eval("-123"))
print(eval("12+3"))
print(eval("12-3"))
# print(eval("a123"))
# print(eval("12a3"))
abc = "123"
print(eval("abc"))

运行结果:

123
<class 'int'>
123
-123
15
9
123

len(string)

'''
原型:
功能:返回字符串的长度(按字符个数计算)
参数:
'''
print(len("This is an apple."))
print(len("This is an apple苹果"))

运行结果:

17
18

lower()

'''
原型:
功能:转换字符串中所有的大写字母为小写
参数:
'''
str1 = "This Is An applE."
str2 = str1.lower()
print(str1, str2)

运行结果:

This Is An applE. this is an apple.

upper()

'''
原型:
功能:转换字符串中所有的小写字母为大写
参数:
'''
str1 = "This Is An applE."
str2 = str1.upper()
print(str1, str2)

运行结果:

This Is An applE. THIS IS AN APPLE.

swapcase()

'''
原型:
功能:将字符串中大写转为小写,小写转为大写
参数:
'''
str1 = "This Is An applE."
str2 = str1.swapcase()
print(str1, str2)

运行结果:

This Is An applE. tHIS iS aN APPLe.

capitalize()

'''
原型:
功能:将字符串中第一个字符转为大写,其余转为小写
参数:
'''
str1 = "This Is An applE."
str2 = str1.capitalize()
print(str1, str2)

运行结果:

This Is An applE. This is an apple.

title()

'''
原型:
功能:得到“标题化”的字符串,每个单词的首字符大写,其余小写
参数:
'''
str1 = "This Is An applE."
str2 = str1.title()
print(str1, str2)

运行结果:

This Is An applE. This Is An Apple.

center(width[, fillchar])

'''
原型:
功能:返回一个指定宽度width的居中字符串,fillchar为填充字符,默认为空格
参数:
'''
str1 = "This Is An applE."
str2 = str1.center(30,"#")
print("*"+str2+"*")

运行结果:

*######This Is An applE.#######*

ljust(width[, fillchar])

'''
原型:
功能:返回一个指定宽度width的左对齐字符串,fillchar为填充字符,默认为空格
参数:
'''
str1 = "This Is An applE."
str2 = str1.ljust(30,"#")
print("*"+str2+"*")

运行结果:

*This Is An applE.#############*

rjust(width,[, fillchar])

'''
原型:
功能:返回一个指定宽度width的右对齐字符串,fillchar为填充字符,默认为空格
参数:
'''
str1 = "This Is An applE."
str2 = str1.rjust(30,"#")
print("*"+str2+"*")

运行结果:

*#############This Is An applE.*

zfill (width)

'''
原型:
功能:返回指定宽度width的右对齐字符串,填充0
参数:
'''
str1 = "This Is An applE."
str2 = str1.zfill(30)
print("*"+str2+"*")

运行结果:

*0000000000000This Is An applE.*

count(str[, beg= 0,end=len(string)])

'''
原型:
功能:返回str在string里面出现的次数,如果beg或者end指定则返回指定范围内str出现的次数
参数:
'''
str1 = "natasha"
str2 = "This is an apple."
print(str2.count(str1,0,20))
str3 = "apple"
print(str2.count(str3,0,20))

运行结果:

0
1

find(str[, beg=0 end=len(string)])

'''
原型:
功能:检测str是否包含在string中,如果指定beg和end,则检测指定范围内是否包含。如果包含返回第一个开始的索引值,否则返回-1
参数:
'''
str1 = "natasha"
str2 = "This is an apple."
res = str2.find(str1)
print(res)
str3 = "apple"
res = str2.find(str3)
print(res)

运行结果:

-1
11

index(str[, beg=0, end=len(string)])

'''
原型:
功能:跟find()一样,区别在于如果str不存在会报异常
参数:
'''
str1 = "natasha"
str2 = "This is an apple."
str3 = "apple"
res = str2.index(str3)
print(res)

res = str2.index(str1)
print(res)

运行结果:

Traceback (most recent call last):
  File "E:/python/第二章/variable.py", line 12, in <module>
    res = str2.index(str1)
ValueError: substring not found
11

rfind(str[, beg=0,end=len(string)])

'''
原型:
功能:类似于find(),只不过从右边开始查找
参数:
'''
str1 = "natasha"
str2 = "This is an apple."
res = str2.rfind(str1)
print(res)
str3 = "apple"
res = str2.rfind(str3)
print(res)

运行结果:

-1
11

rindex(str[, beg=0, end=len(string)])

'''
原型:
功能:类似于index(),只不过从右边开始查找
参数:
'''
str1 = "natasha"
str2 = "This is an apple."
str3 = "apple"
res = str2.rindex(str3)
print(res)

res = str2.rindex(str1)
print(res)

运行结果:

Traceback (most recent call last):
11
  File "E:/python/第二章/variable.py", line 12, in <module>
    res = str2.rindex(str1)
ValueError: substring not found

lstrip()

'''
原型:
功能:截掉字符串左边指定的字符,默认为空格
参数:
'''
str1 = "    This is an apple."
str2 = str1.lstrip()
print(str1)
print(str2)
str3 = "*****This is an apple."
str4 = str3.lstrip("*")
print(str3)
print(str4)

运行结果:

    This is an apple.
This is an apple.
*****This is an apple.
This is an apple.

rstrip()

'''
原型:
功能:截掉字符串右边指定的字符,默认为空格
参数:
'''
str1 = "This is an apple.    "
str2 = str1.rstrip()
print(str1)
print(str2)
str3 = "This is an apple.*****"
str4 = str3.rstrip("*")
print(str3)
print(str4)

运行结果:

This is an apple.    
This is an apple.
This is an apple.*****
This is an apple.

strip([chars])

'''
原型:
功能:在字符串上执行lstrip和rstrip
参数:
'''
str1 = "*****This is an apple.*****"
str2 = str1.strip("*")
print(str1)
print(str2)

运行结果:

*****This is an apple.*****
This is an apple.

split(str="", num=string.count(str))

'''
原型:
功能:str默认是空格,如果字符串开头和结尾都是空格,那么切片的空格是从第二个空格开始,开头和结尾的空格不会被切取,如果str不是默认的空格,那么就要从遇到的第一个字符串为分隔符开始切,如果str在被切割的字符串的开头或者结尾,最后返回的列表开头或结尾的元素为 ''
参数:
'''

str1 = "This#is#an#apple."
wordList = str1.split("#")
print(type(str1))
print(wordList)
print(type(wordList))

运行结果:

<class 'str'>
['This', 'is', 'an', 'apple.']
<class 'list'>

splitlines([keepends])

'''
原型:
功能:按照行('\r','\r\n','\n'),如果keepends为False,不包含换行符,否则保留换行符
参数:
'''
str1 = '''This
is
an
apple
'''
wordList = str1.splitlines()
print(wordList)

运行结果:

['This', 'is', 'an', 'apple']

join(seq)

'''
原型:
功能:按照行('\r','\r\n','\n'),如果keepends为False,不包含换行符,否则保留换行符
参数:
'''
str1 = '''This
is
an
apple
'''
wordList = str1.splitlines()

str2 = " ".join(wordList)
print(str2)

运行结果:

This is an apple

max(str)

'''
原型:
功能:返回字符串中最大的字母
参数:
'''
str1 = "This is an apple."
print(max(str1))

运行结果:

s

min(str)

'''
原型:
功能:返回字符串中最小的字母
参数:
'''
str1 = "thisisanapple"
print(min(str1))

运行结果:

a

replace(old, new [, max])

'''
原型:
功能:将字符串中的old替换成new,如果max指定,则替换不超过max次
参数:
'''
str1 = "This is an apple."
str2 = str1.replace("apple", "banana")
print(str1)
print(str2)

运行结果:

This is an apple.
This is an banana.

maketrans()

'''
原型:
功能:创建字符映射的转换表,对于接受两个参数的,第一个是字符串,表示要转换的字符,第二个也是字符串表示转换的目标
参数:
'''
t = str.maketrans("ag", "12")
print(t)

运行结果:

{97: 49, 103: 50}

translate(table)

'''
原型:
功能:根据str给出的表转换字符串
参数:
'''
t = str.maketrans("ag", "12")

str1 = "This is an apple."
print(str1)
print(str1.translate(t))

运行结果:

This is an apple.
This is 1n 1pple.

isalpha()

'''
原型:
功能:如果字符串至少有一个字符并且所有的字符都是字母返回True,否则返回假
参数:
'''
print("".isalpha())
print("abc".isalpha())
print("abc12".isalpha())

运行结果:

False
True
False

isalnum()

'''
原型:
功能:如果字符串至少有一个字符并且所有的字符都是字母或数字返回True,否则返回假
参数:
'''
print("".isalnum())
print("abc".isalnum())
print("abc12".isalnum())

运行结果:

False
True
True

isupper()

'''
原型:
功能:如果字符串至少有一个字符并且所有的字母都是大写字母返回True,否则返回假
参数:
'''
print("apple".isupper())
print("APPLE".isupper())
print("APPLE#$%".isupper())
print("APPLE123".isupper())
print("".isupper())

运行结果:

False
True
True
True
False

islower()

'''
原型:
功能:如果字符串至少有一个字符并且所有的字母都是小写字母返回True,否则返回假
参数:
'''
print("apple".islower())
print("APPLE".islower())
print("APPLE#$%".islower())
print("APPLE123".islower())
print("".islower())

运行结果:

True
False
False
False
False

istitle()

'''
原型:
功能:如果字符串是标题化的返回True,否则返回False
参数:
'''
print("apple".istitle())
print("APPLE".istitle())
print("APPLE#$%".istitle())
print("APPLE123".istitle())
print("".istitle())

运行结果:

False
False
False
False
False

isdigit()

'''
原型:
功能:如果字符串只包含数字返回True,否则返回False
参数:
'''
print("".isdigit())
print("123".isdigit())
print("abc123".isdigit())

运行结果:

False
True
False

isnumeric()

'''
原型:
功能:如果字符串只包含数字返回True,否则返回False
参数:
'''
print("".isnumeric())
print("123".isnumeric())
print("abc123".isnumeric())

运行结果:

False
True
False

isdecimal()

'''
原型:
功能:检测字符串是否只包含十进制数字
参数:
'''
print("".isdecimal())
print("123".isdecimal())
print("abc123".isdecimal())

运行结果:

False
True
False

isspace()

'''
原型:
功能:如果字符串中只含有空格则返回True,否则返回False
参数:
'''
print("".isspace())
print("   ".isspace())
print(" a".isspace())
print("\t".isspace())
print("\n".isspace())

运行结果:

False
True
False
True
True

startswith(str[, beg=0,end=len(string)])

'''
原型:
功能:检查字符串是否以str开头,是则返回True, 否则返回False。如果指定了beg和gend,则在指定范围内检查
参数:
'''
str1 = "This is an apple."
print(str1.startswith("apple"))

运行结果:

False

endswith(suffix[, beg=0, end=len(string)])

'''
原型:
功能:检查字符串是否以suffix结尾,是则返回True, 否则返回False。如果指定了beg和gend,则在指定范围内检查
参数:
'''
str1 = "This is an apple."
print(str1.endswith("apple"))

运行结果:

False

encode(encoding=‘UTF-8’,errors=‘strict’)

'''
原型:
功能:以encoding指定的编码格式进行编码,如果出错默认报一个ValueError异常,除非errors指定的是igonre或者replace
参数:
'''
str1 = "这是一个苹果"
str2 = str1.encode()
str3 = str1.encode("GBK") #gb2312
print(str1)
print(str2)
print(str3)

运行结果:

这是一个苹果
b'\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe8\x8b\xb9\xe6\x9e\x9c'
b'\xd5\xe2\xca\xc7\xd2\xbb\xb8\xf6\xc6\xbb\xb9\xfb'

bytes.decode(encoding=“utf-8”, errors=“strict”)

'''
原型:
功能:解码
参数:
'''
str1 = "这是一个苹果"
str2 = str1.encode()
str3 = str1.encode("GBK") #gb2312
print(str1)
print(str2.decode("utf-8"))
print(str3.decode("GBK"))

运行结果:

这是一个苹果
这是一个苹果
这是一个苹果

ord()

'''
原型:
功能:获取字符的整数表示
参数:
'''
print(ord("a"))
print(ord("苹"))

运行结果:

97
33529

chr()

'''
原型:
功能:把数字编码转为对应的字符
参数:
'''
print(chr(97))
print(chr(33529))

运行结果:

a
苹

str()

'''
原型:
功能:转成字符串
参数:
'''
print(str(123))
print(str(123.1))
print(type(str(True)))

运行结果:

123
123.1
<class 'str'>

布尔值

一个布尔值只有True、False两种值,要么是True,要么是False

作用:作为真假的判断

b = True
c = False
print(b, c)
print(type(b), type(c))

运行结果:

True False
<class 'bool'> <class 'bool'>

空值

是python里一个特殊的值,用None表示。None不能理解为0,因为0是有意义的,而None是一个特殊的控制,没有实际意义。

作用:定义个变量时,不知道初始值要赋值成什么,那么就赋值为None,当有确定值在进行赋值操作。

d = None
print(d)
print(type(d))

运行结果:

None
<class 'NoneType'>

变量的类型问题

变量的类型要根据对应的数据来判断具体是什么类型的,变量的类型是变化的。

a = None
a = 1
a = "apple"
a = False
print(type(a))

运行结果:

<class 'bool'>

练习

1.控制台输入一个年份,判断是否是闰年

闰年:公历年份是4的倍数的,一般是闰年。(如2004年就是闰年)

num1 = int(input("请输入年份:"))
num2 = 0
if num1 % 4 == num2 :
    print(num1, "是闰年!")
else:
    print(num1, "不是闰年!")

运行结果:

请输入年份:2019
2019 不是闰年!

2.控制台输入一个时间,打印该时间的下一秒

例如:22:22:01下一秒是22:22:02

print("格式例如:22:22:01")
time = input("请输入一个时间:")
wordList = time.split(":")
h = int(wordList[0])
m = int(wordList[1])
s = int(wordList[2])

s += 1
if s == 60:
    m += 1
    s = 0
    if m == 60:
       h += 1
       m = 0
       if h == 24:
           h = 0
print("%.2d:%.2d:%.2d"%(h,m,s))

运行结果:

格式例如:22:22:01
请输入一个时间:22:59:59
23:00:00
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值