0
点赞
收藏
分享

微信扫一扫

Python编程 字符串的方法

  • 作者简介:一名在校计算机学生、每天分享Python的学习经验、和学习笔记。 

  • 个人主页:网络豆的主页

目录

​​前言​​

​​一字符串​​

​​1.字符串常见操作(熟悉)​​

​​ 2.S.find(sub)、 S.index(sub)​​

​​3.replace(old, new[, count])​​

​​4.S.split(sep=None)​​

​​5.S.startswith 与 S.endswith​​

​​6.S.upper 与 S.lower​​

​​7.S.strip​​

​​8.S.join​​

前言

本章将会从python 编程 字符串的常见操作去进行讲解。

一字符串

1.字符串常见操作(熟悉)

S.find(sub) --> 返回该元素最小的索引
S.index(sub) --> 返回该元素最小的索引
S.replace(old, new[, count]) --> 替换
S.split(sep=None) --> 以sep来分割字符串,并返回列表。sep默认为None,分割默认为空格
S.startswith(prefix[, start[, end]]) --> 判断字符串是否以前缀开始,返回为bool值。
S.endswith(suffix[, start[, end]]) --> 判断字符串是否以尾缀结束,返回为bool值。
S.lower() --> 将字符串全部转为小写
S.upper() --> 将字符串全部转为大写
S.strip([chars]) --> 默认去掉字符串左右的空格
S.isalpha() --> 判断字符串是否全为字母,返回的是bool值
S.isdigit() --> 判断字符串是否全为数字,返回的是bool值
S.isalnum() --> 判断字符串是否全为数字或者字母,不存在特殊字符,返回的是bool值
S.join(iterable) --> 将序列中的元素以指定的字符连接生成一个新的字符串

 2.S.find(sub)、 S.index(sub)

s1 = "hello python"
print(s1.find("e")) # S.find(sub[, start[, end]]) -> int 整数 返回最小索引位置

print(s1.find("o")) #输出得4

print(s1.find("c")) # 没有C得负一 Return -1 on failure.

print(s1.rfind("o")) #得10


print(s1.index("c")) #ValueError: substring not found index与find作用一模一样.但是
区别在于当通过S.index查询 不存在的字符串时会报错,而s.find()返回—1

3.replace(old, new[, count])

s2 = "hello oldoldamy"

#old————>beautiful
print(s2.replace("old","beautiful")) #得hello beautifulbeautifulamy 全部替换掉

print(s2.replace("old","beautiful",1)) #得hello beautifuloldamy count:指定替换次数

print(s2) #得 hello oldoldamy copy of S,所以意味着没有改变s2本身

4.S.split(sep=None)

s3 = "hello everybody yeyeye!"

# 以空格将三个单词进行拆分为列表的元素
print(s3.split(" ")) #['hello', 'everybody', 'yeyeye!']
#返回列表
print(type(s3.split(" "))) #<class 'list'>

5.S.startswith 与 S.endswith

s4 = "hello everybody yeyeye!"

print(s4.startswith("he")) #用于判断字符串以什么前缀开始,返回为

#S.startswith(prefix[, start[, end]]) -> bool

print(s4.endswith("ye!")) #判断以什么尾椎结束的

6.S.upper 与 S.lower

s5 = "n"
print(s5.upper()) #得N
# Return a copy of the string converted to uppercase

s6 = "Y"
print(s6.lower()) #得y

7.S.strip

s7 = "    一代    枭雄       "
print(s7.strip()) #得一代 枭雄 去除首部以及尾部的空格
print(s7.replace(" ","")) #一代枭雄 去除中间空格

8.S.join

s8 = "你好某某同学bababalalallaal"

# 实现:"你 好"
# 字符串序列-->一个个取出它的子元素-->可以迭代的(iterable)
print(" ".join(s8)) #得你 好 某 某 同 学 b a b a b a l a l a l l a a l



li = ["你好", "世界"]

# 实现:"你好 世界"
print(" ".join(li)) #得 你好 世界

创作不易,求关注,点赞,收藏,谢谢~

举报

相关推荐

0 条评论