python字符串内建函数-replace、split

python字符串内建函数-replace、split

4、replace

函数功能:replace函数用于将字符串中的部分旧字符串替换成新的字符串。

返回值:该函数的返回值是字符串中的部分旧字符串替换成新的字符串之后生成的新字符串。

函数语法str.replace(old,new[,count])

  • old:将被替换的旧字符串
  • new:新字符串,用于替换旧字符串
  • count:可选参数,替换不超过count次
# replace
str1 = "hello world I love python"
new_str1 = str1.replace("hello","hi")
print(new_str1) # hi world I love python

new_str1 = str1.replace("o","m")
print(new_str1) # hellm wmrld I lmve pythmn

new_str1 = str1.replace("o","m",2)
print(new_str1) # hellm wmrld I love python

5、split

函数功能:split函数通过指定分隔符对字符串进行切片,如果参数maxsplit具有指定值,则仅分隔最多maxsplit个字符串。

返回值:该函数的返回值是分隔后的字符串列表

函数语法str.split(sep = None,maxsplit = -1)

  • sep:分隔符,默认为所有的空字符,包括空格、换行、制表符等
  • maxsplit:分割次数
# split
str1 = "hello world I love python"
print(str1.split()) # ['hello', 'world', 'I', 'love', 'python']
print(str1.split("o")) # ['hell', ' w', 'rld I l', 've pyth', 'n']
print(str1.split("o",2)) # ['hell', ' w', 'rld I love python']

注:python字符串内建函数还有很多,查看更多点击下面链接:

  • python 字符串内建函数

  • python 字符串内建函数-find、index、count

  • python字符串内建函数-capitalize、title、upper

  • python字符串内建函数-startwith、endwith

  • python字符串内建函数-ljust、rjust、center

  • python字符串内建函数-lstrip 、rstrip、strip

你可能感兴趣的:(python,#,基础知识)