输出结果:H,!
### 2,index
s = “你好,世界!”
使用index()方法获取字符串中指定字符的索引
index_of_char = s.index(‘好’)
print(index_of_char) # 输出: 1
使用index()方法获取字符串中指定子串的索引
index_of_substring = s.index(‘你好’)
print(index_of_substring) # 输出: 0
### 3,count,len
`count`用来统计某元素出现的次数,`len`用来计算字符串的长度:
str = “Hello world!”
使用count统计“o”出现的次数
print(str.count(“o”)) # 输出:2
#使用len计算长度
print(len(str)) # 输出:12
## 二,replace()
`replace()` 用于在字符串中查找所有指定的子字符串,并使用指定的替换字符串替换它们。
(注意:不会对原始字符串进行修改,而是返回一个替换好的新字符串)
基本语法:
str.replace(old, new, [count])
>
> `old`:要被替换的**子字符串**。
> `new`:用于替换的**新子字符串**。
> `count`:(可选)指定要替换的最多`old`子字符串的个数。如果未指定或为负数,则替换所有出现。
>
>
>
示例:
text = “Hello, world!”
new_text = text.replace(“world”, “Python”)
print(new_text) # 输出 “Hello, Python!”
## 三,split()
`split()`方法:用于将一个字符串分割成一个字符串列表
(注意:不会修改原始字符串,而是返回一个新的列表)
基本语法:
str.split(separator, maxsplit)
>
> `separator`:指定用作分割符的子字符串。默认是一个空格。
> `maxsplit`:(可选)指定要分割的次数。默认是 -1,意味着分割所有出现。
>
>
>
示例:
text = “Python is fun”
words = text.split(" ")
print(words) # 输出 [‘Python’, ‘is’, ‘fun’]
text = “apple,banana,orange,grape”
fruits = text.split(“,”)
print(fruits) # 输出 [‘apple’, ‘banana’, ‘orange’, ‘grape’]
## 四,strip()
`strip()`方法:用于删除字符串开头和结尾的指定字符
(注意:不会修改原始字符串,而是返回一个新的字符串)
基本语法:
strip([chars])
>
> `chars`:可选参数,表示需要删除的字符。如果未提供此参数,则默认删除空格。
> (在 Python 的 `strip()` 方法中,回车符(`\r`)和换行符(`\n`)都属于空格的一种形式,都会被默认删除。)
>
>
>
示例:
不提供chars
s = " Hello, World! "
s = s.strip()
print(s) # 输出:Hello, World!
提供chars:“,”
s = “,Hello, World!,”
s = s.strip(“,”)
print(s) # 输出:Hello, World!
提供字符串:“12”
str = “12hello world21”
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!