5_string

可变与不可变

Values are immutable.Thus, numbers, strings, tuples are immutable.

What does it mean for immutable or mutable --- assignment, modification, reference

1.assignment

variable ---> computer memory ---> object

2.modification

how to modify an immutable object (x is immutable)

x = "abc"
x = "def"

how to modify a mutable object (x is mutable)

a.make a new assignment:

x = [1,2,3]
x = [4,5,6]

b.make a modification by methods for lists.

x = [1,2,3]
del x[0]
del x[1]
del x[2]
x.append(4)
x.append(5)
x.append(6)

3.reference

x = "abc"
y = x
x = "def"

x = [1,2,3]
y = x
del x[2]
x.append(4)
print(y)

#[1,2,4]

   

x = [1,2,3]
y = x[:]
del x[2]
x.append(4)
print(y)

#[1,2,3]

 string

 字符串是不可变的数据类型,若要修改:

greeting = 'Hello, world!'
new_greeting = 'J' + greeting[1:]
print(new_greeting)

#Jello, world!

 .title(),.upper(),.lower()

.title()返回“标题化”的字符串,.upper()将字符串全部大写,.lower()将字符串全部小写。

三者均不改变字符串。

name = 'ada lovelace'
print(name.title())
print(name.lower())
print(name.upper())
print(name)

"""
Ada Lovelace
ada lovelace
ADA LOVELACE
ada lovelace
"""

.strip()函数

用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

str.strip([chars])

"""
chars -- 移除字符串头尾指定的字符序列。
"""

指定字符只要存在就被删除,不论字符在原字符串中的顺序如何。

str = "123abcrunoob321"
print (str.strip( '12' ))

"""
3abcrunoob3
"""

 .lstrip()和.rstrip()分别对应只删除左边和只删除右边

.find()

检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围(左闭右开),则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

str.find(str, beg=0, end=len(string))

.startwith()

检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

str.startswith(str, beg=0,end=len(string))

 .split()

通过指定分隔符对字符串进行切片,分割次数为num,返回值为列表。

默认初始条件下空格和回车都会被分割

str.split(str="", num=string.count(str))

应用例子:

txt = "Google#Runoob#Taobao#Facebook"
x = txt.split("#", 1)
print (x)

"""
['Google', 'Runoob#Taobao#Facebook']
"""

.format()函数

格式化字符串,可以接受不限个参数,位置可以不按顺序。

"{} {}".format("hello", "world")
"{0} {1}".format("hello", "world")
"{1} {0} {1}".format("hello", "world")

"""
1.不设置指定位置,按默认顺序:'hello world'
2.设置指定位置:'hello world'
3.设置指定位置:'world hello world'
"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值