Python 字符串详解

2019-04-03  本文已影响0人  浅宇落

字符串替换

str = "hello world"
str = str.replace("world", "Python") # 替换
print(str)
打印结果: hello Python

字符串拼接

str = "hello world"
str1 = "你好"
str2 = str + str1 # 拼接
print(str2)
打印结果: hello world你好
str1 = "你好"
print("你好, 这是北京: %s" % str1)
打印结果: 你好, 这是北京: 你好

字符串按照字符切割

str = "hello world, pthon, 你好"
str_list = str.split(", ")
print(str_list)
打印结果: ['hello world', 'pthon', '你好']

字符串比较

str = "你好"
str1 = "你好"
print(str == str1)
打印结果: True

字符串长度

str = "你好"
len = len(str) # 字符串的长度
print(len)
打印结果: 2

字符串是否包含某字符

str = "你好"

result = "你" in str # 是否包含
print("result: %s" % result)
打印结果:result: True

result1 = "你" not in str # 是否不包含
print("result1: %s" % result1)
打印结果:result1: False

字符串截取

str = "你好123456"
result = str[1:3]
print(result)
打印结果:好1
str = "你好123456"
result = str[:]
print(result)
打印结果:你好123456
str = "你好123456"
result = str[1:]
print(result)
打印结果:好123456
str = "你好123456"
result = str[:3]
print(result)
打印结果:你好1
str = "你好123456"
result = str[-3:]
print(result)
打印结果:456

字符串大小写

str = "dfmkFFFsadfm"
result = str.upper()
print(result)
打印结果:DFMKFFFSADFM
str = "dfmkFFFsadfm"
result = str.lower()
print(result)
打印结果:dfmkfffsadfm
上一篇下一篇

猜你喜欢

热点阅读