一字符串的连接join

str={"hello","world","hello","china"}

result=";".join(str)
print(result)
运行结果:world;china;hello

 

二字符串的截取-切片,split

1切片
str="hello world"
print(str[0:3])
运行结果:hel
2split
str="Bod said:1,2,3,4"
print(str.split(",",2))
运行结果:

Python 字符串处理常用方法

 


 

三字符串的比较==,!=

str1=1
str2="1"
if str1==str2:
print("相同")
else:
print("不相同")
if str(str1)==str2:
print("相同")
else:
print("不相同")
运行结果:

不相同
相同

2startswith,endwith的用法

word="hello world"
print(word.startswith("hello"))
print(word.endswith("ld",6))
#从索引6~11搜索ld
print(word.endswith("ld",6,len(word)))
运行结果:

Python 字符串处理常用方法

四字符串的反转

def reverse(s):
out=""
li=list(s)
for i in range(len(li),0,-1):
out+="".join(li[i-1])
return out
if __name__=="__main__":
print(reverse("hello world,everyone"))
运行结果:

Python 字符串处理常用方法

五字符串的查找和替换

1查找find和rfind

sentence="This is a apple"
print(sentence.find("a"))
print(sentence.rfind("a"))
运行结果:

Python 字符串处理常用方法

2替换replace

sentence="hello world,hello China"
print(sentence.replace("hello","hi"))
print(sentence.replace("hello","hi",1))
print(sentence.replace("abc","hi"))
运行结果:

Python 字符串处理常用方法

 


六字符串与日期的转换

Python 字符串处理常用方法

运行结果:

Python 字符串处理常用方法

 

 




相关文章:

  • 2021-11-13
  • 2020-10-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-16
猜你喜欢
  • 2021-08-28
  • 2021-08-20
  • 2021-06-28
  • 2022-12-23
  • 2022-12-23
  • 2019-06-04
  • 2021-12-10
相关资源
相似解决方案