Python字符串函数-处理字符串的常用函数及用法示例
Python中字符串是一种常用的数据类型,通常用来表示文本信息。Python为字符串提供了很多常用的函数,以便我们方便地处理字符串。
1. len() 函数
len()函数可以返回字符串的长度。
示例代码:
str = "Hello World!" print(len(str)) # 打印出 12
2. capitalize() 函数
capitalize函数可以将字符串的 个字符变成大写字母,其余字符变为小写字母。这个函数不会改变原来字符串的值,而是会返回新的字符串。
示例代码:
str = "this is a sample string." new_str = str.capitalize() print(new_str) # 输出 This is a sample string.
3. lower() 函数
lower()函数可以将字符串中的所有字符转换成小写字母。这个函数不会改变原来字符串的值,而是会返回新的字符串。
示例代码:
str = "THIS IS A SAMPLE STRING." new_str = str.lower() print(new_str) # 输出 this is a sample string.
4. upper() 函数
upper()函数可以将字符串中的所有字符转换成大写字母。这个函数不会改变原来字符串的值,而是会返回新的字符串。
示例代码:
str = "this is a sample string." new_str = str.upper() print(new_str) # 输出 THIS IS A SAMPLE STRING.
5. replace() 函数
replace()函数可以将字符串中的一个子串替换成另一个字符串。这个函数会返回一个新的字符串,替换后的结果不会影响原来的字符串。
示例代码:
str = "this is a sample string."
new_str = str.replace("sample", "example")
print(new_str) # 输出 this is a example string.
6. find() 函数
find()函数可以在字符串中查找一个子串,并返回其在字符串中的位置。如果没有找到,则返回-1。
示例代码:
str = "this is a sample string."
position = str.find("sample")
print(position) # 输出 10
7. split() 函数
split()函数可以将一个字符串按照指定的分隔符分成多个子字符串,并且返回一个分割后的列表。
示例代码:
str = "this is a sample string."
str_list = str.split(" ")
print(str_list) # 输出 ['this', 'is', 'a', 'sample', 'string.']
8. join() 函数
join()函数可以将一个列表中的元素拼接成一个字符串。其中,列表中的元素必须是字符串才能进行拼接。
示例代码:
str_list = ['this', 'is', 'a', 'sample', 'string.'] str = " ".join(str_list) print(str) # 输出 this is a sample string.
9. strip() 函数
strip()函数可以去除字符串两端的空格字符。这个函数不会改变原来字符串的值,而是会返回新的字符串。
示例代码:
str = " This is a sample string. " new_str = str.strip() print(new_str) # 输出 This is a sample string.
总之,Python提供了很多方便处理字符串的函数,通过这些函数的使用可以简化我们的编程。在实际应用中,我们可以根据需要灵活的使用字符串函数,完成更复杂的任务。
