Python + 字符串

表示

可以通过几种不同的方式表示字符串。如单引号(’…’)或双引号("…")。如果你想要分几行输入字符串,并且希望行尾的换行符自动包含到字符串当中,可以使用三对引号:"""…""" 或 ‘’’…’’’ 。

>>> s = "I am Chinese"
>>> s
'I am Chinese'
>>> s = 'I am Chinese'
>>> s = "Here is a line \
... split in two lines"
>>> s
'Here is a line split in two lines'
>>> s = "Here is a line \n split in two lines"
>>> s
'Here is a line \n split in two lines'
>>> print(s)
Here is a line
 split in two lines
 >>> print("""\
... Usage: thingy [OPTIONS]
...      -h                        Display this usage message
...      -H hostname               Hostname to connect to
... """)
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

方法

每一个字符串对象都有几个可用的内建方法,我们已经使用过一些了,比如 s.split()。

>>> s = "shi yan lou"

# 方法 title() 返回字符串的标题版本,即单词首字母大写其余字母小写
>>> s.title()
'Shi Yan Lou'

# 方法 upper() 返回字符串全部大写的版本,反之 lower() 返回字符串的全部小写版本
>>> z = s.upper()
>>> z
'SHI YAN LOU'
>>> z.lower()
'shi yan lou'

# 方法 swapcase() 返回字符串大小写交换后的版本
>>> s = "I am A pRoGraMMer"
>> s.swapcase()
'i AM a PrOgRAmmER'

# 方法 isalnum() 检查所有字符是否只有字母和数字
>>> s = "jdwb 2323bjb"
>>> s.isalnum()
False
>>> s = "jdwb2323bjb"
>>> s.isalnum()
True

# 方法 isalpha() 检查字符串之中是否只有字母
>>> s = "SankarshanSir"
>>> s.isalpha()
True
>>> s = "Sankarshan Sir"
>>> s.isalpha()
False
copy

#  方法 isdigit() 检查字符串是否所有字符为数字
>>> s = "1234"
>>> s.isdigit()
True

# 方法 islower() 检查字符串是否所有字符为小写
>>> s = "ShiYanLou is coming"
>>> s.islower() 
False

# 方法 istitle() 检查字符串是否为标题样式
>>> s = "Shiyanlou Is Coming"
>>> s.istitle()
True

# 方法 isupper() 检查字符串是否所有字符为大写
>>> s = "CHINA"
>>> s.isupper()
True

# 我们可以使用 split() 分割任意字符串,split() 允许有一个参数,用来指定字符串以什么字符分隔(默认为 " "),它返回一个包含所有分割后的字符串的列表
>>> s = "We all love Python"
>>> s.split()
['We', 'all', 'love', 'Python']
>>> x = "shiyanlou:is:waiting"
>>> x.split(':')
['shiyanlou', 'is', 'waiting']

# 方法 join() 使用指定字符连接多个字符串,它需要一个包含字符串元素的列表作为输入然后连接列表内的字符串元素
>>> "-".join("GNU/Linux is great".split())
'GNU/Linux-is-great'	# 我们基于空格 " " 分割字符串 "GNU/Linux is great",然后用 "-" 连接它们。

剥离

# 方法strip(chars),用来剥离字符串首尾中指定的字符,它允许有一个字符串参数,这个参数为剥离哪些字符提供依据。不指定参数则默认剥离掉首尾的空格和换行符
>>> s = "  a bc\n "
>>> s.strip()
'a bc'

# 使用 lstrip(chars) 或 rstrip(chars) 只对字符串左或右剥离
>>> s = "www.foss.in" 
>>> s.lstrip("cwsd.") #删除在字符串左边出现的'c','w','s','d','.'字符
'foss.in'
>>> s.rstrip("cnwdi.") #删除在字符串右边出现的'c','n','w','d','i','.'字符
'www.foss'

文本搜索

字符串有一些方法能够帮助你搜索字符串里的文本或子字符串。find() 能帮助你找到第一个匹配的子字符串,没有找到则返回 -1。

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

回文检测

回文是一种无论从左还是从右读都一样的字符序列。比如 “madam”。如下示例

#!/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")

输出结果为:

$ python3 palindrome.py                                                                                               
Please enter a string: 12121
The string is a palindrome
$ python3 palindrome.py                                                                                               
Please enter a string: 123
The string is not a palindrome

单词计数

常用格式化操作符有:

%s 字符串(用 str() 函数进行字符串转换)

%r 字符串(用 repr() 函数进行字符串转换)

%d 十进制整数

%f 浮点数

%% 字符“%

一个简单的示例如下:

>>> s = "Python is a language."
>>> print("The number of words in the line are %d" % (len(s.split(" "))))
The number of words in the line are 4
>>> 

参考资料

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值