python学习 -- String

# 修改字符串中的内容:

1. 使用 format() 方法:

使用方法一:

str1 = "this is a {}"
str2 = str1.format("book")
print(str2)  # this is a book

需要注意的是使用format方法对字符串进行修改时,不会在原有的变量中修改,而是生成一个新变量去修改;

使用方法二:

str = "{} is a good {}"
str2 = str.format("jason", "boy")
print(str2)  # jason is a good boy

当字符串中含有多个{ }时,按照索引顺序依次修改;

使用方法三:

str = "we need a {tool}"
str2 = str.format(tool = "pen")
print(str2)  # we need a pen

根据字符串中的关键字(# {tool})来修改; 

2. 使用{变量}赋值方法:

str1 = "machel"
str2 = "tokyo"
print(f"{str1} lives in {str2}")  # machel lives in tokyo

字符串前加f,字符串中变量使用{变量}格式,将字符串外的变量值修改到字符串中;

# join的使用:

使用join可以将可迭代对象拼接为字符串:

list_1 = ["s", "m", "i", "l", "e"]
tuple_1 = ("a", "c", "e")
str1 = "".join(list_1)
print(str1)  # smile
str2 = "|".join(tuple_1)
print(str2)  # a|c|e

"".josin() 拼接可迭代对象,中间无间隔内容

"|".jsoin() 拼接可迭代对象,两个元素中间以|间隔;

# split 的使用:

使用split方法可以将字符串做切片处理:

str = "blue bird"
result = str.split("u")
print(result)  # ['bl', 'e bird']

需要注意的是:用作切分的内容("u")会被切除掉,不展示在切片结果中;切分结果以列表形式返回;

# replace 的使用:

使用replace方法将字符串中的指定内容进行替换:

str = "Harry has a secret"
str2 = str.replace("Harry", "Ron")
print(str2)  # Ron has a secret

# strip 的使用:

strip方法可以将字符串首位部分的空格去掉:

str = " log is important for us. "
str2 = str.strip()
print(str2)  # "log is important for us."

# len() 方法 : 用来获取参数字符串的字符个数,该函数并不是字符串类型特有的,而是一个通用函数 格式

a = "long"
print(len(a))  # 4

# count() 方法: 返回输入值字符串里出现的次数,可以指定开始和结束位置

b = "long time ago"
print(b.count("g"))  # 2
print(b.count("g", 0, 4)) # 1

# index() 方法:检查输入值是否存在于字符串中,如果有,则返回其索引值,如果没有则会报错,同样可以指定开始和结束位置,同样是左闭右开(start, end],当要找的值存在多个时,只返回第一个的索引值

c = "coca cola"
print(c.index("c"))  # 0 第一个c的索引值
print(c.index("c", 1, 4))  # 2  从索引为1开始,找到的第一个c的索引值
print(c.index("k"))  # ValueError: substring not found

# rindex() 方法:作用和使用方法同index(),只是查找时从字符串右侧开始查找

d = "water"
print(d.rindex("e"))  # 3
print(d.rindex("t", 0, 2))  # ValueError: substring not found

# find() 方法: 查询输入值是否存在于字符串中,如果存在则返回索引值,不存在则返回 -1, 同样支持指定开始和结束位置,也是左闭右开 (start, end ]

e = "watch"
print(e.find("a"))  # 1
print(e.find("b"))  # -1
print(e.find("t", 0, 3))  # 2 

# rfind() 方法:作用和find一致,只是查找时从字符串右侧开始查找;

f = "light"
print("f", f.rfind("g"))  # 2
print("f", f.rfind("k"))  # -1
print("f", f.rfind("i", 2, 5))  # -1

# replace(old, new, max) 方法:将字符串中指定的值换为输入值,可以指定最大更换次数;

g = "coca cola"
print(g.replace("c", "C"))  # CoCa Cola
print(g.replace("c", "C", 2))  # CoCa cola

# startswith() 方法:检查字符串是否以输入值开头,如果是则返回True,否则返回False,同样可指定开始和结束位置,指定后在指定范围内检查, 左闭右开;

h = "glasses"
print("h", h.startswith("gl"))  # True
print("h", h.startswith("gl", 2, 7))  # False
print("h", h.startswith("as", 2, 7))  # True

# endswith() 方法:作用类似startwith(),同样也可指定开始结束位置;

i = "earphone"
print("i", i.endswith("ne"))  # True
print("i", i.endswith("ne", 1, 3))  # False
print("i", i.endswith("ar", 1, 3))  # True

# isalpha() 方法:如果字符串至少存在一个字符,且所有字符都是字母,则返回True,否则返回False;

j = "toys"
j1 = "y0ys"
j2 = ""
j3 = "@a"
print("j", j.isalpha())  # True
print("j", j1.isalpha())  # False
print("j", j2.isalpha())  # False
print("j", j3.isalpha())  # False

# isdigit() 方法:当字符串中只包含数字时,则返回True,否则返回False,但不支持负数和小数;

k = "12345"
k1 = "123ef"
k2 = ""
k3 = "123.4"
print("k", k.isdigit())  # k True
print("k", k1.isdigit())  # k False
print("k", k2.isdigit())  # k False
print("k", k3.isdigit())  # k False

# isalnum() 方法: 当字符串至少存在一个字符,且其中所有字符都是字母或者数字格式时,则返回True,否则返回False;

l = "abc"
l1 = "123"
l2 = "abc123"
l3 = " "
l4 = "!123"
l5 = "!abc"
print("l", l.isalnum())  # l True
print("l", l1.isalnum())  # l True
print("l", l2.isalnum())  # l True
print("l", l3.isalnum())  # l False
print("l", l4.isalnum())  # l False
print("l", l5.isalnum())  # l False

# isspace() 方法:如果string中只包含空格,则返回True,否则返回False,用法:xx.isspace()

a = "    "
b = "  a  "
print(a.isspace())  # True
print(b.isspace())  # False

# isupper() 方法: 如果string中包含至少一个区分大小写的字符,并且这些(区分大小写的)字符都是大写,则返回True,否则返回False,用法: xxx.isupper()

a = "123"
b = "Abs"
c = "ABC"
print(a.isupper())  # False
print(b.isupper())  # False
print(c.isupper())  # True

 # islower() 方法:同上方 isupper() 方法相反,同法相同;

a = "123"
b = "Abs"
c = "abc"
print(a.islower())  # False
print(b.islower())  # False
print(c.islower())  # True

# istitle() 方法:如果string是标题化的(所有单词的首字母是大写),则返回True,否则返回False,用法: xxx.istitle()

a = "1 2 A"
b = "Abc Efg Hij"
c = "ABC Efg Hij"
print(a.istitle())  # True
print(b.istitle())  # True
print(c.istitle())  # False

# capitalize() 方法:把字符串中的第一个字符大写,用法 xxx.capitalize()

a = "123"
b = "Abc"
c = "ab cd"
print(a.capitalize())  # 123
print(b.capitalize())  # Abc
print(c.capitalize())  # Ab cd

# title() 方法:返回标题化的string,所有单词均以大写开始,其余字母小写,用法 xxx.title()

a = "Jason Is Smart."
b = "we need some help"
c = "123 number"
print(a.title())  # Jason Is Smart.
print(b.title())  # We Need Some Help
print(c.title())  # 123 Number

# upper() 方法:将string中的小写字母转换为大写,用法 xxx.upper()

a = "12 ab"
b = "star"
c = "GOAL"
print(a.upper())  # 12 AB
print(b.upper())  # STAR
print(c.upper())  # GOAL

# lower() 方法: 将string中的大写字母转换为小写,用法 xxx.lower()

a = "12 AB"
b = "star"
c = "GOAL"
print(a.lower())  # 12 ab
print(b.lower())  # star
print(c.lower())  # goal

# center() 方法:返回一个原字符串居中,并使用空格填充至长度width的新字符串,如果指定fillchar 参数,则使用指定的字符填充,fillchar 参数的长度只能为1,用法:x.center(width, fillchar)

a = "All We Fight For"
b = a.center(20)
c = a.center(20, "-")
d = a.center(1)
print(b)  # "  All We Fight For  "
print(c)  # "--All We Fight For--"
print(d)  # "All We Fight For"

# ljust() 方法:用法同上面的center() 方法,只是字符串是左对齐

a = "All We Fight For"
b = a.ljust(20)
c = a.ljust(20, "-")
d = a.ljust(1)
print(b)  # "All We Fight For    "
print(c)  # "All We Fight For----"
print(d)  # "All We Fight For"

# rjust() 方法:用法同上面center() 方法,只是字符串是右对齐

a = "All We Fight For"
b = a.rjust(20)
c = a.rjust(20, "-")
d = a.rjust(1)
print(b)  # "    All We Fight For"
print(c)  # "----All We Fight For"
print(d)  # "All We Fight For"

# strip()  方法:删除字符串两侧的空白字符,如果指定char参数,则删除左右两侧指定的字符,用法 x.strip(char)

a = "  All We Fight For  "
print(a.strip())  # "All We Fight For"
b = "All We Fight For"
print(b.strip("Ar"))  # ll We Fight Fo

# lstrip() 方法:用法同strip() 方法,只是只删除左侧空白字符,如果指定参数,则删除左侧指定字符

a = "  All We Fight For  "
print(a.lstrip())  # "All We Fight For  "
b = "All We Fight For"
print(b.lstrip("Ar"))  # ll We Fight For

# rstrip() 方法:用法同strip() 方法,只是只删除右侧空白字符,如果指定参数,则删除右侧指定字符

a = "  All We Fight For  "
print(a.rstrip())  # "  All We Fight For"
b = "All We Fight For"
print(b.rstrip("Ar"))  # All We Fight Fo

# split() 方法:以sep为分隔符分割string,如果指定maxsplit参数,则只分割maxsplit次,用法xx.split(sep, maxsplit)

a = "Abcadadaux"
print(a.split('a'))  # ['Abc', 'd', 'd', 'ux']
print(a.split('a', 2))  # ['Abc', 'd', 'daux']

# splitlines() 方法: 使用换行符\n 分割string,如果指定keepends参数,则结果中会保留\n符号,用法: xx.splitlines(keepends)

a = "ab\ncd\nef"
print(a.splitlines())  # ['ab', 'cd', 'ef']
print(a.splitlines(True))  # ['ab\n', 'cd\n', 'ef']

# partition() 方法:从sep出现的第一个位置起,把string分成一个3元素的元组,元组中的3元素分别为(sep前, sep, sep后),如果srting中不包含sep,则3元素为(srting, , ),后面两元素用空字符串代替,用法xxx.partition(sep)

a = "today is a nice day"
print(a.partition("is"))  # ('today ', 'is', ' a nice day')
print(a.partition("IO"))  # ('today is a nice day', '', '')

# rpartition() 方法:用法同上面partition() 方法,只是从右开始寻找第一个sep的出现位置;

a = "today is a nice day"
print(a.rpartition("is"))  # ('today ', 'is', ' a nice day')
print(a.rpartition("IO"))  # ('', '', 'today is a nice day')

#  +号 将两个字符串连接生成一个新字符串, + 号两侧必须都是字符串,用法:str1 + str2

print("Hello" + "World")  # HelloWorld
print("Hello" + "123")  # Hello123
print("Hello" + 123)  # TypeError: can only concatenate str (not "int") to str

# *号, 将字符串重复N次后生成一个新字符串,用法:str*N

a = "nice"
print(a*3)  # nicenicenice

# encode() 方法:使用encode指定的字符集,对string进行编码,转换为二进制格式字符串,用法:xx.encode(encoding)

a = "nice"
b = "天空"
print(a.encode("gbk"))  # b'nice'
print(b.encode("gbk"))  # b'\xcc\xec\xbf\xd5'

# decode() 方法:使用encoding指定的字符集,对string进行解码,转换为字符串对象,string必须是二进制格式,用法 xx.decode(encoding)

a = b'nice'
b = b'\xcc\xec\xbf\xd5'
print(a.decode("gbk"))  # nice
print(b.decode("gbk"))  # 天空

# 切片操作:对字符串按指定的范围进行截取,得到一个子字符串,指定范围时,起始下标必须小于结束下标,且子字符串不包含结束下标,用法:str[start: end: step]

s = "abcdefg"

# 普通切片
print(s[0: 2])  # ab
# 省略范围
print(s[0:])  # abcdefg
print(s[: 2])  # ab
print(s[:])  # abcdefg
# 指定步长
print(s[::1])  # abcdefg
print(s[::2])  # aceg
# 负下标
print(s[-3: -1])  # ef
# 负步长
print(s[-1: -3: -1])  # gf
# 逆序
print(s[::-1])  # gfedcba

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值