【Python】字符串

2020-09-08  本文已影响0人  四叶草_2d32

知识点

字符串是python中最常见的数据类型

字符串的表示

字符串常见的API:

>>> s = "shi yan lou"
>>> s.title()
'Shi Yan Lou'

>>> z = s.upper()
>>> z
'SHI YAN LOU'
>>> z.lower()
'shi yan lou'

>>> s = "We all love Python"
>>> s.split()
['We', 'all', 'love', 'Python']
>>> x = "shiyanlou:is:waiting"
>>> x.split(':')
['shiyanlou', 'is', 'waiting']

>>> "-".join("GNU/Linux is great".split())
'GNU/Linux-is-great'

字符串剥离:

>>> s = "  a bc\n "
>>> s.strip()
'a bc'


>>> s = "  a bc\n "
>>> s.strip()
'a bc'

文本搜索

>>> s = "faulty for a reason"
>>> s.find("for")
7
>>> s.find("fora")
-1
>>> s.startswith("fa") # 检查字符串是否以 fa 开头
True
>>> s.endswith("reason") # 检查字符串是否以 reason 结尾
True

回文检查

#!/usr/bin/env python3
s = input("Please enter a string: ")
z = s[::-1]  #把输入的字符串s 进行倒序处理形成新的字符串z
if s == z:
    print("The string is a palindrome")
else:
    print("The string is not a palindrome")

格式化操作符%
格式符为真实值预留位置,并控制显示的格式。常用的有:

单词计数
对用户输入的一行文本进行单词计数。

#!/usr/bin/env python3
s = input("Enter a line: ")
print("The number of words in the line are %d" % (len(s.split(" "))))
上一篇 下一篇

猜你喜欢

热点阅读