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

Python中字符串相关函数。

发布时间:2023-06-10 03:08:30

Python中有许多字符串相关的函数,包括字符串的基本操作,如字符串的连接、替换、查找等,还包括字符串的格式化等高级操作。下面一一介绍这些函数。

1.字符串的连接

字符串的连接可以使用“+”运算符,例如:

str1 = 'hello'

str2 = 'world'

result = str1 + str2

print(result)

输出结果为:

helloworld

另外,我们还可以使用join()方法来连接字符串,例如:

strs = ['hello', 'world']

result = ' '.join(strs)

print(result)

输出结果为:

hello world

2.字符串的分割

字符串的分割可以使用split()方法,例如:

str = 'hello world'

result = str.split()

print(result)

输出结果为:

['hello', 'world']

另外,我们还可以指定分割符,例如:

str = 'hello,world'

result = str.split(',')

print(result)

输出结果为:

['hello', 'world']

3.字符串的替换

字符串的替换可以使用replace()方法,例如:

str = 'hello world'

result = str.replace('world', 'Python')

print(result)

输出结果为:

hello Python

4.字符串的查找

字符串的查找可以使用find()或index()方法,例如:

str = 'hello world'

result1 = str.find('world')

result2 = str.index('world')

print(result1, result2)

输出结果为:

6 6

两个方法的区别是:当查找的字符串不存在时,find()方法返回-1,而index()方法抛出异常。

5.字符串的大小写转换

字符串的大小写转换可以使用upper()和lower()方法,例如:

str = 'Hello World'

result1 = str.upper()

result2 = result1.lower()

print(result1, result2)

输出结果为:

HELLO WORLD hello world

6.字符串的首字母大写

字符串的首字母大写可以使用capitalize()方法,例如:

str = 'hello world'

result = str.capitalize()

print(result)

输出结果为:

Hello world

7.字符串的居中对齐

字符串的居中对齐可以使用center()方法,例如:

str = 'hello world'

result = str.center(20, '*')

print(result)

输出结果为:

*******hello world*******

8.字符串的格式化

字符串的格式化可以使用format()方法,例如:

str = 'My name is {} and I am {} years old.'

result = str.format('Tom', 18)

print(result)

输出结果为:

My name is Tom and I am 18 years old.

另外,我们还可以使用{}和%运算符来格式化字符串,例如:

str1 = 'Tom'

str2 = 18

result1 = 'My name is %s and I am %d years old.' % (str1, str2)

result2 = 'My name is {} and I am {} years old.'.format(str1, str2)

print(result1, result2)

输出结果为:

My name is Tom and I am 18 years old. My name is Tom and I am 18 years old.

以上就是Python中常用的字符串函数,这些函数不仅可以方便我们的字符串操作,而且也能够为我们的代码提供更多的灵活性和扩展性。