字符串处理函数
函数-len()
- 返回字符串x的长度,也可返回其他组合数据类型的元素个数
- 例如:
x = len("12345")
print(x)
y = len("abcdef")
print(y)
函数-str()
x = str("12345")
print(x)
y = str("abcdef")
print(y)
函数-chr()
x = chr(48)
print(x)
y = chr(97)
print(y)
函数-ord()
- 返回单字符x表示的Unicode(常见的utf-8)编码
- 例如:
x = ord("0")
print(x)
y = ord("a")
print(y)
函数-hex()
x = hex(12345)
print(x)
函数-oct()
x = oct(12345)
print(x)
字符串处理方法
函数-lower()
x = "My name is cjl. My favorite language is python"
print(x.lower())
函数-upper()
x = "My name is cjl, my favorite language is python"
print(x.upper())
函数-split(sep)
- 能够根据sep分隔字符串,分割后的内容以列表类型返回。
- 例如:
x = "My name is cjl, my favorite language is python"
print(x.split())
print(x.split('e'))
函数-count(sub)
x = "My name is cjl, my favorite language is python"
print(x.count('a'))
函数-replace(old, new)
- 返回字符串副本,所有old字符串被替换为new
- 例如:
x = "My name is cjl, my favorite language is python"
print(x.replace('a', 'b'))
函数-center(width, fllchar)
x = "My name is cjl, my favorite language is python"
print(x.center(30, *))
函数-strip()
- 从字符串变量中去掉其左侧和右侧的字符
- lstrip(), rstrip(), strip()
- 例如:
x = "My name is cjl, my favorite language is python"
print(x.strip())
print(x.strip('n'))
函数-join(iter)
x = "My name is cjl, my favorite language is python"
print(x.join('#*'))
数字类型转换
函数-int(x)
x = 3.1415926
print(type(x), int(x), type(int(x)))
函数-float(x)
x = 3
print(type(x), float(x), type(float(x)))
函数-str(x)
x = 3.1415926
print(type(x), str(x), type(str(x)))