Python基础知识:整理4 字符串的相关操作

字符串也是不可修改的数据容器,只读

1. 通过下标取值

# 1. 通过下标取值
# 从左往右: 0,1,2,3, ...
# 从右往左:-1, -2, -3,-4, ...
str = "jfvvfdkbnf"
print(str[1])   # f
print(str[-2])  # n
print("---------------------")

 

2.  查找特定字符串的下标索引值

"""
    语法:
        字符串.index(字符串)
"""
str = "xyudgfu and jdafjfis"
value = str.index("and")    # 8
print(value)
print("---------------------")

3. 字符串的替换

"""
    语法:
        字符串.replace(字符串1, 字符串2)
        功能: 将字符串内所有的字符串1,替换为字符串2
        注意:不是修改字符串的本身,而是得到了一个新的字符串
"""
str = "xyudgfu and jdafjfis"
new_str = str.replace("j", "J")    # xyudgfu and JdafJfis
print(new_str)
print("-----------------------")

4. 字符串的分割

"""
    语法:字符串.split(分割字符串)
    功能:按照指定的分割字符串,将字符串分为多个字符串,并存入列表对象中
    注意:注意字符串的本身没有变,而是得到了一个列表对象
"""
str = "hello python world"
new_str = str.split(" ")    # ['hello', 'python', 'world']
print(new_str)
print("-------------------------")

5. 字符串的规整操作1(可以去除前后空格以及回车符)

"""
    语法: 字符串.strip()
    会有默认值,如果不传参数的话,会将字符串的前后空格去掉
"""
str = " fdgd "
new_str = str.strip()    # fdgd
print(new_str)
print("---------------------------")

6. 字符串的规整操作2(取出前后指定的字符串)

"""
    语法:
        字符串.strip(指定的字符串)
"""
str = "12hfjgjrhf and fjgj21"
new_str = str.strip("12")  # 结果是  "hfjgjrhf and fjgj"
# 传入的是 "12", 实际上就是 "1"和"2"都会被移除
print(new_str)
print("----------------------------")

7. 统计字符串中某某字符串出现的次数

str = "jfsghjjjjjppdrg"
num = str.count("g")   # 2
print(num)
print("----------------------------")

8. 统计字符串的长度

str = "123456"
num = len(str)   # 6
print(num)
print("-------------------------------")

你可能感兴趣的:(Python,python)