字符串

本贴最后更新于 718 天前,其中的信息可能已经时异事殊

一、特性

1、字符串不可修改

test_str = "hello python"
print(id(test_str))

test_str = "hello java"
print(id(test_str))

两次打印的id结果:

2885581349680
2885581092464

可以看到结果不一致,说明重新赋值后,虽然名字一样,但是两次指向的内存地址不一样

image.png

2、字符串是有序的

3、可迭代的

test_str = "hello"

for i in test_str:
    print(i)

结果为:

h
e
l
l
o

二、字符串的创建

1、单引号括起来

str_test = 'python'

2、双引号括起来

str_test1 = "java"

3、三引号括起来

str_test2 = """哈哈哈"""

str_test3 = '''hahh'''

三、字符串操作

1、字符串的访问

(1)通过索引访问:变量名[index]

正序索引从0开始,倒序索引从-1开始

test_str = "python"

image.png

print(test_str[0])

结果为:p

(2)字符串切片:字符串[起始索引:结束索引:步长]

test_str = "python"

print(test_str[0:3])

结果为:

pyt

(3)字符串切片注意点

(4)倒序切片:步长前写负号(-)为倒序切片

正序索引和倒序索引最好不要混着用

test_str = "hello"

print(test_str[-1:-3:-1])

结果为:

llo

(5)字符串反转:字符串[::-1]

test_str = "hello"

print(test_str[::-1])

结果为:

olleh

四、字符串拼接

test_str1 = "hello"

test_str2 = "python"

test_str3 = test_str1 + test_str2

print(test_str3)

五、字符串重复输出

print("--" * 2)

--会重复输出2次

六、字符串转义

1、换行符\n

2、转义符\

print("hello \\n python")

结果为:

hello \n python

3、原串输出r

print(r"hello \n python")

结果为:

hello \n python

七、字符串常用方法

1、将所有字母大写.upper()

2、将所有字母小写.lower()

3、将字符串首字母大写.capitalize()

4、大小写互换.swapcase()

5、所有单词首字母大写.title()

6、计算某个字符在字符串中出现的次数count(统计对象,开始索引,结束索引),开始索引和结束索引可以省略,表示全部字符串(规则同切片)

7、统计字符串长度len(字符串)

8、返回查找对象的第一个索引值.find("查找对象")

9、返回查找对象的最后一个索引值.rfind("查找对象")

10、判断字符串是否都是大写.isupper()

11、判断是否都是小写.islower()

12、判断字符串是否有字母或者数字.isalnum()

13、判断字符串是否是空格.isspace()

14、判断字符串是否都是数字.isdigit()

15、判断是否以指定的字符开头.startswith("指定字符")

16、判断是否以指定的字符结尾.endswith("指定字符")

回帖
请输入回帖内容 ...