欢迎访问宙启技术站
智能推送

Python字符串函数的使用及示例:len(), str(), format()等

发布时间:2023-06-09 03:20:27

Python中的字符串函数非常丰富,可以用于字符串的创建、格式化、查询、截取、替换等操作。在本文中,我们将介绍一些常用的字符串函数及其使用方法和示例。

1. len()函数

len()函数用于返回字符串的长度,即字符串中字符的个数。

示例:

text = "Hello World!"

print(len(text))

输出结果为:12

2. str()函数

str()函数用于将对象转换为字符串。

示例:

age = 18

print("My age is " + str(age))

输出结果为:My age is 18

3. format()函数

format()函数用于格式化输出字符串。

示例:

name = "Tom"

age = 20

print("My name is {0}, and I am {1} years old.".format(name, age))

输出结果为:My name is Tom, and I am 20 years old.

4. lower()函数

lower()函数用于将字符串中所有大写字母转换为小写字母。

示例:

text = "HELLO WORLD!"

print(text.lower())

输出结果为:hello world!

5. upper()函数

upper()函数用于将字符串中所有小写字母转换为大写字母。

示例:

text = "hello world!"

print(text.upper())

输出结果为:HELLO WORLD!

6. strip()函数

strip()函数用于去除字符串开头和结尾的空格。

示例:

text = "   Hello World!   "

print(text.strip())

输出结果为:Hello World!

7. replace()函数

replace()函数用于替换字符串中的指定子串。

示例:

text = "hello world!"

print(text.replace("world", "python"))

输出结果为:hello python!

8. find()函数

find()函数用于查找字符串中指定子串的位置。

示例:

text = "hello world!"

print(text.find("world"))

输出结果为:6

9. split()函数

split()函数用于将字符串分割为多个子串,并将子串存储在一个列表中。

示例:

text = "hello,world!"

print(text.split(","))

输出结果为:['hello', 'world!']

10. isdigit()函数

isdigit()函数用于判断字符串是否只包含数字。

示例:

text = "1234"

print(text.isdigit())

输出结果为:True

总结

Python中的字符串函数非常丰富,常用的字符串函数包括len()、str()、format()、lower()、upper()、strip()、replace()、find()、split()和isdigit()等。了解这些函数的使用方法和示例可以帮助开发者更加方便快捷地处理字符串相关的任务。