Python课程第七天_上午_课程笔记(字符串的基础功能String_Basic)

Day_07_AM_String_Basic_Class_Note

# String字符串
#   用引号包裹的就是字符串, 可以是单引号或双引号

# 基本操作

# 1.创建字符串
s = 'Hello John'

# 2.长度
print(len(s))  # 空格和标点也算字符

# 索引
print(s[0])  # 跟列表一样
print(s[1])
print(s[-1])

# 4.切片(一次取多个)
print(s[6:])  # John
print(s[4:7])  # o J
print(s[::-1])  # nhoJ olleH

# 5.拼接
print('亲' + "我")  # 亲我

# 重复
print('给个好评!' * 3)

# 7.成员
print('a good' in 'today is a good day!')  # True, 只要是长字符串里连续的一串都可以

# 8.遍历
s = 'hello'
for c in s:
    print(c)  # 每个字符

for i in range(len(s)):
    print(i, s[i])  # 下标

for i, c in enumerate(s):
    print(i, c)  # 下标,字符

# 9.字符串是不肯变的
s = 'hello'
# s[0] = 'a'  # TypeError: 'str' object does not support item assignment
s = s + 'world'
print(s)  # 'hello world', 实际上是创建了一个新的字符串 'hello world' 上面的'hello'没有改掉,然 然后s指向了这个新的字符串, 原来的没用了内存会清空(原来的还在也不会占用多少空间)

猜你喜欢

转载自blog.csdn.net/weixin_44298535/article/details/107634554
今日推荐