大数跨境
0
0

Python之字符串操作大全(15种方法)

Python之字符串操作大全(15种方法) 码途钥匙
2024-10-15
0

1. 重复输出字符串

print('x' * 20)

输出:xxxxxxxxxxxxxxxxxxxx

2. 通过索引获取字符串

print('hello world'[2:5])

输出:llo

3. in 判断字符是否在字符串内

print('e' in 'hello world')

输出:True

4. % 格式化输出

print('%s world'%'hello')

输出:hello world

5. + 字符串拼接

a = 'hello 'b = ' world'c = a + bprint(c)

输出:hello world

6. join 拼接字符串

a = 'hello'b = ' world'c = ' '.join([a,b])print(c)

输出:hello world

7. count 统计字符串中指定字母的出现次数

a = 'www.baidu.com'print(a.count('w'))

输出:3

8.center 居中

a = "www.baidu.com"b = a.center(50, '*')print(b)

输出:******************www.baidu.com*******************

9. startswith 判断字符串是否以指定字符串开头

a = 'www.baidu.com'print(a.startswith('www'))

输出:True

10.find 找制定字符出现的第一个位置

a = 'www.baidu.com'b = a.find('u')print(b)

输出:8

11. format 格式化字符串 

a = '{0}.baidu.{1}'.format('www', 'com')print(a) #输出www.baidu.com string = 'hello world {xxx} {ppp}'b = string.format(xxx='xxx', ppp = 'ppp')print(b) #输出hello world xxx ppp c = string.format_map({'xxx':'xxx', 'ppp':'ppp'})print(c) #输出:hello world xxx ppp

12. lower 将字符串所有字符小写输出

a = 'Wang Da Bai'print(a.lower())

输出:wang da bai

13. upper 将字符串所有字符大写输出

a = 'Wang Da Bai'print(a.upper())

输出:WANG Da BAI

14. strip 去除掉字符串后的空格

a = 'wang da bai 'print(a.strip())  #去除尾部空格

输出:wang da bai

15. repalce 将指定字符替换为另一个指定字符

a = "wang da bai"b = a.replace('w', '*')print(b) #输出: *ang da bai c = 'wangdabai'.replace('d', 'xxxxxx', 1)print(c) #输出 wangxxxxxxabai


【声明】内容源于网络
0
0
码途钥匙
欢迎来到 Python 学习乐园!这里充满活力,分享前沿实用知识技术。新手或开发者,都能找到价值。一起在这个平台,以 Python 为引,开启成长之旅,探索代码世界,共同进步。携手 Python,共赴精彩未来,快来加入我们吧!
内容 992
粉丝 0
码途钥匙 欢迎来到 Python 学习乐园!这里充满活力,分享前沿实用知识技术。新手或开发者,都能找到价值。一起在这个平台,以 Python 为引,开启成长之旅,探索代码世界,共同进步。携手 Python,共赴精彩未来,快来加入我们吧!
总阅读43
粉丝0
内容992