<2>Python开发——字符串(str)

字符串(str)

操作方法

字符串是不可变对象,所以任何操作对原字符串是不会有任何影响

首字母大写

s1 = "python"
print(s1.capitalize())

全部转换为小写

s1 = "PYTHON"
print(s1.lower())

全部转换为大写

s1 = "python"
print(s1.upper())

大小写互相转换

s1 = "Python1"
print(s1.swapcase())

特殊字符隔开首字母大写

s1 = "wsl by love"
print(s1.title())

居中

s1 = "wsl"
print(s1.center(5, "*")) # 拉长成5,把原字符串放中间,其余位置补*

 去左右空格

s1 = "  wsl  "
print(s1.strip())

去右边空格

s1 = "  wsl  "
print(s1.rstrip())

字符串替换

# 默认替换全部
s1 = "wslwslwslwsl"
print(s1.replace("wsl", "by"))

# 指定替换次数
s1 = "wslwslwslwsl"
print(s1.replace("wsl", "by", 2))

字符串切割

s1 = "wslwslwslwsl"
print(s1.split("w")) # 如果切割符在左右两端,那么一定会出现空字符串

s1 = """
    wsl
    wsl
"""
print(s1.split("
"))

 格式化输出

s1 = "我叫%s, 今年%d , 我喜欢%s" % ("wsl", 18, "by")
print(s1)
s2 = "我叫{}, 今年{} , 我喜欢{}".format("wsl", 18, "by")
print(s2)
s3 = "我叫{0}, 今年{2} , 我喜欢{1}".format("wsl", 18, "by")
print(s3)
s4 = "我叫{name}, 今年{age} , 我喜欢{love}".format(name="wsl", age=18, love="by")
print(s4)

查找

# 判断开头和结尾
s1 = "wslwslwslwsl"
print(s1.startswith("wsl"))

s1 = "wslwslwslwsl"
print(s1.endswith("wsl"))

# 字符出现的次数
s1 = "wslwslwslwsl"
print(s1.count('w'))

# 查找位置
s1 = "wslwslwslwsl"
print(s1.find("wsl"))

字符串判断

# 是否由字母和数字组成
s1 = "123b"
print(s1.isalnum())

# 是否由字母组成
s1 = "123b"
print(s1.isalpha())

# 是否由数字组成,不包括小数点
s1 = "123b"
print(s1.isdigit())

# 计算字符串的长度

len(s1)

字符串遍历
s1 = "wsl"
for i in s1:
    print(i)

 字符串的拼接

字符串只有 + *,字符串 + 就是拼接,* 就是重复字符串

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"
print(message)
# Hello, Ada Lovelace!

print("str" * 5) # strstrstrstrstr

# 但是字符串不能和其他类型进行运算
print("Wshile" + 520) # TypeError: must be str, not int

 制表符或换行符来添加空白

print("Languages:
	Python
	C
	JavaScript")

使用字符串时避免语法错误

message = "One of Pythen's strengths is its diverse community."
print(message)

message2 = 'One of Python's strengths is its diverse community.'
print(message2)

 切片和索引

s1 = "python最牛"
print(s1[0])
print(s1[-1])
print(s1[0:3])
print(s1[1:])
print(s1[-5:-1])
print(s1[:])

步长

s1 = "python最牛"
print(s1[1::2])
原文地址:https://www.cnblogs.com/Wshile/p/12914869.html