Python中常用的字符串函数及使用实例
Python 中有很多常用的字符串函数,可以方便地进行字符串的操作和处理。下面就来介绍几个常见的字符串函数及其使用实例。
1. str()函数
str()函数可以将其他数据类型转化为字符串类型。
例:
num = 123
str_num = str(num)
print(str_num)
输出结果:123
2. len()函数
len()函数可以返回字符串的长度。
例:
str1 = 'hello, world!'
str_len = len(str1)
print(str_len)
输出结果:13
3. upper()函数
upper()函数可以将字符串转化为大写形式。
例:
str2 = 'hello, world!'
str_upper = str2.upper()
print(str_upper)
输出结果:HELLO, WORLD!
4. lower()函数
lower()函数可以将字符串转化为小写形式。
例:
str3 = 'HELLO, WORLD!'
str_lower = str3.lower()
print(str_lower)
输出结果:hello, world!
5. capitalize()函数
capitalize()函数可以将字符串首字母大写。
例:
str4 = 'hello, world!'
str_cap = str4.capitalize()
print(str_cap)
输出结果:Hello, world!
6. strip()函数
strip()函数可以去除字符串中的空白字符(包括换行符、制表符、空格等)。
例:
str5 = ' hello, world! '
str_strip = str5.strip()
print(str_strip)
输出结果:hello, world!
7. replace()函数
replace()函数可以替换字符串中的指定字符。
例:
str6 = 'hello, world!'
str_replace = str6.replace('world', 'python')
print(str_replace)
输出结果:hello, python!
8. split()函数
split()函数可以将字符串按照指定的分隔符分成若干部分,并返回一个包含所有部分的列表。
例:
str7 = 'hello,world,python'
str_split = str7.split(',')
print(str_split)
输出结果:['hello', 'world', 'python']
9. join()函数
join()函数可以将一个列表中的所有元素按照指定的字符串连接成一个字符串。
例:
str8 = ['hello', 'world', 'python']
str_join = ','.join(str8)
print(str_join)
输出结果:hello,world,python
10. format()函数
format()函数可以将一些数据格式化成字符串。
例:
name = 'Tom'
age = 18
str_format = 'My name is {}, and I am {} years old.'.format(name, age)
print(str_format)
输出结果:My name is Tom, and I am 18 years old.
总结:
以上就是 Python 中常用的字符串函数及使用实例。这些函数可以方便地进行字符串的操作和处理,提高了代码的效率和可读性,值得我们在实际编程中加以运用。
