Python字符串函数的简单介绍和用法
Python中字符串是不可变的序列,可以使用字符串函数对字符串进行各种操作。在Python中有很多字符串函数可供使用,以下是其中一些常用的字符串函数介绍和用法。
1. len(str)
len函数用于返回字符串的长度,即字符串中字符的个数。例如:
str = "hello world"
print(len(str))
输出结果为:11
2. str.strip()
strip函数用于去除字符串头尾指定的字符(默认为空格),返回去除后的字符串。例如:
str = " hello world "
print(str.strip())
输出结果为:hello world
3. str.upper()/str.lower()
upper函数用于将字符串中的所有小写字母转化为大写字母,返回新的字符串。lower函数用于将字符串中的所有大写字母转化为小写字母,返回新的字符串。例如:
str = "Hello World"
print(str.upper())
print(str.lower())
输出结果为:
HELLO WORLD
hello world
4. str.replace(old, new[, count])
replace函数用于将字符串中的某一字符或字符串替换为新的字符或字符串,并返回新的字符串。可以指定替换的次数(可选)。例如:
str = "Hello World"
print(str.replace("World", "Python"))
print(str.replace("l", "s", 1))
输出结果为:
Hello Python
Heslo World
5. str.split([sep[, maxsplit]])
split函数用于将字符串按照指定字符或字符串分割成列表,并返回列表。可以指定分割的次数(可选)。例如:
str = "Hello World"
print(str.split())
print(str.split("l", 1))
输出结果为:
['Hello', 'World']
['He', 'lo World']
6. str.isdigit()
isdigit函数用于检测字符串是否只包含数字,是则返回True,否则返回False。例如:
str1 = "12345"
str2 = "abcde"
print(str1.isdigit())
print(str2.isdigit())
输出结果为:
True
False
7. str.isupper()/str.islower()
isupper函数用于检测字符串中所有的字母是否为大写,是则返回True,否则返回False。islower函数用于检测字符串中所有的字母是否为小写,是则返回True,否则返回False。例如:
str1 = "HELLO WORLD"
str2 = "hello world"
print(str1.isupper())
print(str2.islower())
输出结果为:
True
True
8. str.startswith(prefix[, start[, end]])
startswith函数用于判断字符串是否以指定的字符串开头,返回True或False。可以指定字符串的起止位置(可选)。例如:
str = "Hello World"
print(str.startswith("Hello"))
print(str.startswith("World", 6))
输出结果为:
True
True
9. str.endswith(suffix[, start[, end]])
endswith函数用于判断字符串是否以指定的字符串结尾,返回True或False。可以指定字符串的起止位置(可选)。例如:
str = "Hello World"
print(str.endswith("World"))
print(str.endswith("ello", 1, 5))
输出结果为:
True
True
10. str.join(iterable)
join函数用于将一个可迭代对象中的元素用指定的字符串连接起来,返回一个新的字符串。例如:
str = "-"
list = ["a", "b", "c"]
print(str.join(list))
输出结果为:a-b-c
以上是部分Python字符串函数的介绍和用法,这些函数非常实用,可以帮助我们更加方便地操作字符串。另外,在使用Python字符串函数时,需要注意函数的参数和返回值,以及一些特殊情况的处理。
