史上最全的字符串增、添、删、改!!!你要的这里都有!!!

目录

1.字符串的创建

2.字符串的增加

(1)字符串的追加

(2)字符串的局部添加

 

3.字符串的删除

4.字符串的修改

作者的话


1.字符串的创建

(1)赋值法

>>>string='This is a demo for python.'
>>>string1="This is a demo for python."
>>>string2='''This is a demo for python.'''
>>>string3="""This is a demo for python."""
>>>string
'This is a demo for python.'
>>>string1
'This is a demo for python.'
>>>string2
'This is a demo for python.'
>>>string3
'This is a demo for python.'

(2)str()方法

>>>a=123456
>>>type(a)
<class 'int'>
>>>str(a)
'123456'
>>>type(str(a))
<class 'str'>

问题:

在赋值定义时,通过上述例子会发现' '、" "、''' '''、""" """都能创建一个字符串那它们之间又有什么区别和联系呢?

一般情况下任意两个之间都可以实现嵌套使用的,但却不能嵌套自身,空口无凭,我们来看例子。

string='This "is" a demo for python.'
string1="This 'is' a demo for python."
print(string)
print(string1)

This "is" a demo for python.
This 'is' a demo for python.

其他的当然也是如此,这里便不一一列举。

python3 字符串添加 python字符串增加_python3 字符串添加

这里我们再' '内部又嵌套了一对' '结果出现了错误,出现了SyntaxError的语法错误,也就是说这种语法类型是不被python解释器认可的。

总结:

在字符串的创建过程中大致分为两种:直接赋值定义、通过str()函数实现。


2.字符串的增加

(1)字符串的追加

1)加法和

>>>str1='python'
>>>str2='1234'
>>>str1+str2
'python1234'

2)嵌套引号

python3 字符串添加 python字符串增加_嵌套_02

问题:

对于这种情况我们分别计算一下字符串长度和它们各自的id。

python3 字符串添加 python字符串增加_经验分享_03

python3 字符串添加 python字符串增加_经验分享_04

可以看出字符串长度都是完全相同的,也就是说对于这种情况而言在两个引号间存在空白,python解释器是不会为其分配空间的,并且对于python解释器而言它认为它们是只想同一个内存空间的,大可放心使用。

3).join()追加

python3 字符串添加 python字符串增加_经验分享_05

4)格式化追加

①format()方法

python3 字符串添加 python字符串增加_python_06

②%s方法

python3 字符串添加 python字符串增加_嵌套_07

这里需要注意两字符串之间是否含有空格在于%s与%s之间是否含有空格,这里也列举出来了。

5)重叠追加

python3 字符串添加 python字符串增加_经验分享_08

(2)字符串的局部添加

1)开头结尾的增加

对于只在开头和结尾进行增加一个或多个字符的形式,完全可以采用上述追加的方式进行,只需略微更改字符串的顺序即可,这里不再过多叙述。

2)中间部分一个或多个字符的插入

python3 字符串添加 python字符串增加_字符串_09


3.字符串的删除

(1)del 整体删除

python3 字符串添加 python字符串增加_python_10

(2)特定字符删除

①.pop()方法

str1='This is a demo for python'
list_str=list(str1)
list_str.pop(1)
list_str=''.join(list_str)
print(list_str)

结果:

Tis is a demo for python

②.replace()方法

python3 字符串添加 python字符串增加_经验分享_11

③del方法

python3 字符串添加 python字符串增加_python3 字符串添加_12

④re.sub()方法

python3 字符串添加 python字符串增加_python_13

关于re.sub()其他用法请读者自行查询其他资料。

4.字符串的修改

1).replace()方法

python3 字符串添加 python字符串增加_python3 字符串添加_14

2)list()方法

python3 字符串添加 python字符串增加_python_15


作者的话

由于小编也有着各种各样的事情要处理,整个过程也是经历了两天的时间才完成,在整个过程中为了让读者能有更好的阅读体验,小编也尝试更改了好几种编程工具,所以可能会看起来有些不一致,但整个内容是完整的同时也是正确的,在这里你肯定能找到你以前所不知道或不是很清楚的地方,在这里预祝大家学习愉快。