Python中的字符串

本文介绍了Python中string模块的常用常量及函数,如查找子字符串、去除标点符号、大小写转换等,并通过实例展示了如何统计文本文件中各单词的出现频率。

string模块中的常量:

import string

string.digits:找出字符串中所有数字

string.letters:找出字符串中所有字母

string.lowercase:找出字符串中所有小写字母

string.uppercase:与上相反

string.printable:可打印字符的字符串

string.punctuation:找出字符串中的所有的标点

string中的函数:

str.find(sub_string):在str中查找sub_string,返回sub_string所在位置最左端索引,没有找到返回-1

str.find(sub_string, index1,index2):也可选择起始点和终点

char.join(string):在str中插入符号char,结果另存到一个字符串中,原字符串不变

相反的,str.split(char):以char作为分隔符,将str分隔成序列,存储到列表中

str.lower():str中的字母都变成小写

str.title():str中的字母除首字母大写,其他小写。=====等价于string.capwprdss(str),不同的是capwords是string模块中的函数,需要import string

str.replace(source_str, dest_str),返回匹配后被替换的字符串,原字符串不变

str.strip():去掉str两头空格的字符串,原字符串保持不变。

str.strip(string.punctuation):去掉字符串中的所有标点符号

举个例子帮助理解,例子出处为“编程小白的第一本Python入门书”


with open(path,'r') as text:
words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
words_index = set(words)   //去重 
counts_dict = {index:words.count(index) for index in words_index}   //存储的是单词以及单词出现的次数,单词是键,次数是值
for word in sorted(counts_dict,key=lambda x: counts_dict[x],reverse=True):           //以字典中的值为排序的参数
print('{} -- {} times'.format(word,counts_dict[word]))         //打印单词以及单词出现的次数    




Python中的字符串是一种不可变的序列类型,用于表示文本数据。字符串可以通过单引号(')、双引号(")或三引号('''或""")来创建。三引号字符串可以跨越多行,常用于多行字符串和注释。 字符串Python中是序列的一种,所以它支持一些通用的序列操作,比如索引、切片、乘法和成员资格测试等。 下面是字符串的一些常见操作: 1. 索引与切片:通过索引可以访问字符串中的特定字符,通过切片可以获取字符串的一部分。 ```python s = "Hello, world!" print(s[0]) # 输出 'H' print(s[1:5]) # 输出 'ello' ``` 2. 字符串连接:可以使用加号(+)来连接两个字符串。 ```python s1 = "Hello" s2 = "world" print(s1 + ", " + s2) # 输出 'Hello, world' ``` 3. 重复:使用乘法操作符(*)可以重复字符串。 ```python print("Python" * 3) # 输出 'PythonPythonPython' ``` 4. 成员资格测试:使用in和not in来检查某个字符串是否包含在另一个字符串中。 ```python print('H' in "Hello") # 输出 True print('z' not in "Python") # 输出 True ``` 5. 转义字符:在字符串中可以使用反斜杠(\)来引入特殊字符,如换行(\n)、制表符(\t)等。 ```python print("Hello\nPython") # 输出 'Hello' 后跟一个换行,然后是 'Python' ``` 6. 原始字符串:在字符串前加上前缀r或R表示原始字符串,它不会处理字符串中的转义字符。 ```python print(r"\n") # 输出 '\n' 而不是换行 ``` 7. 字符串方法:Python提供了许多字符串方法,例如upper(), lower(), split(), replace(), find(), format()等,用于处理字符串数据。 ```python s = "hello, world" print(s.upper()) # 输出 'HELLO, WORLD' print(s.split(",")) # 输出 ['hello', ' world'] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值