字符串--常用操作方法--修改

2022/8/13 23:26:42

本文主要是介绍字符串--常用操作方法--修改,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

所谓修改字符串,指的就是通过函数的形式修改字符串中的数据。

1. replace()替换:

  语法:字符串序列.replace(旧子串,新子串,替换次数)

  注意:替换次数如果查出子串出现次数,则替换次数为该子串出现次数。

mystr = "hello world and itcast and itheima and Python"

# replace() 把and换成he
# replace函数有返回值,返回值是修改后的字符串。
# 结果:hello world he itcast he itheima he Python
new_str = mystr.replace('and', 'he')
# 结果:hello world he itcast and itheima and Python
new_str = mystr.replace('and', 'he', 1)
# 替换次数如果超出子串出现次数,表示替换所有这个子串
# 结果:hello world he itcast he itheima he Python
new_str = mystr.replace('and', 'he', 10)

print(mystr)
print(new_str)

  注意:数据按照是否能直接修改分为可变类型和不可变类型两种。字符串类型的数据修改的时候不能改变原有字符串,

     属于不能直接修改数据的类型即是不可变类型。

2.split()按照指令字符分割字符串

  语法:字符串序列.split(分割字符,num)

  注意:num表示的是分割字符出现的次数,即将来返回数据个数为num+1个。  

mystr = "hello world and itcast and itheima and Python"

# split() -- 分割,返回一个列表, 丢失分割字符
# 结果:['hello world ', ' itcast ', ' itheima ', ' Python']
list1 = mystr.split('and')
# 结果:['hello world ', ' itcast ', ' itheima and Python']
list1 = mystr.split('and', 2)
# 结果:['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
list1 = mystr.split(' ')
# 结果:['hello', 'world', 'and itcast and itheima and Python']
list1 = mystr.split(' ', 2)
print(list1)

  注意:如果跟个字符是原有字符串中的子串,分割后则丢失该子串。

3.join()用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串。

  语法:字符或子串.join(多字符串组成的序列)

# join() -- 合并列表里面的字符串数据为一个大字符串
my_list = ['aa', 'bb', 'cc']

# aa...bb...cc
# 结果:aa...bb...cc
new_str = '...'.join(my_list)
print(new_str)

4.capitalize()将字符串第一个字符转换成大写

 

mystr = "hello world and itcast and itheima and Python"

# 字符串中第一个字母改成大写,其他都改成小写
new_str1 = mystr.capitalize()
# Hello world and itcast and itheima and python
print(new_str1)

 

5.title()将字符串每个单词首字母转换成大写

 

mystr = "hello world and itcast and itheima and Python"

new_str2 = mystr.title()
# 结果:Hello World And Itcast And Itheima And Python
print(new_str2)

 

6.lower()将字符串中大写转小写

 

mystr = "hello world and itcast and itheima and Python"

new_str3 = mystr.lower()
# 结果:hello world and itcast and itheima and python
print(new_str3)

 

7.upper()将字符串中小写转大写

 

mystr = "hello world and itcast and itheima and Python"

new_str4 = mystr.upper()
# 结果:HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
print(new_str4)

 

8.lstrip()删除字符串左侧空白字符

 

 

9.rstrip()删除字符串右侧空白字符

 

10.strip()删除字符串两侧空白字符

 

 

11.ljust()返回一个原字符串左对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。

  语法:字符串序列.ljust(长度,填充字符)

 

12.rjust()返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。语法和ljust()相同。

 

13.center()返回一个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。语法和ljust()相同。

 



这篇关于字符串--常用操作方法--修改的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程