Python序列——字符串

知识点一: 连接操作符(+)

对于字符串来说,这个操作不如把所有得子字符串放到一个列表或可迭代对象中,然后调用一个join方法来把所有的内容连接在一起节约内存

例:' '.join(('I', 'love', 'U'))

类似的,推荐使用列表类型的extend()方法来把两个或者多个列表对象合并。

知识点二: 序列类型函数

len()

返回字符串的字符数

max() and min()

返回最大或最小的字符(按照ASCII码值排列)

enumerate()
s = 'love'
for i, t in enumerate(s):
    print i, t

0 l
1 o
2 v
3 e
zip()
s , t = '0123', 'love'
zip(s, t)

[('0', 'l'), ('1', 'o'), ('2', 'v'), ('3', 'e')]

知识点三: 字符串类型内建++方法++

例:
- string.join(seq): 以string作为分隔符,将seq中所有的元素(字符串表示)合并为一个新字符串。
- string.endwith(obj, beg=0, end= len(string)): 检查字符串是否以obj结束,如果beg或者end指定,则检查指定的范围内是否以obj结束,如果是,返回True,否则返回False。
- string.find(str, beg=0, end=len(string)): 检查str是否包含在string中,如果beg和end指定范围,则检查是否包含在指定范围内,如果是返回++开始的索引值++,否则++返回-1++。
- string.index(str, beg=0, end=len(string)): 跟find()方法一样,只不过如果str不在string中会报++一个异常++。
- string.replace(str1, str2, num=string.count(str1)) :把string中的str1替换成str2,如果num指定,则替换不超过num次。
- string.split(str="", num=string.count(str)): 以str为分隔符切片string,如果num有指定值,则仅分隔num个子字符串。

### Python 字符串处理方法和函数 #### 字符串定义 字符串Python 中最常用的数据类型之一,它们可以用单引号或双引号来表示[^1]。 ```python single_quoted_string = 'Hello, world!' double_quoted_string = "Hello, universe!" ``` #### 基本字符串操作函数 ##### 拼接字符串 可以通过加号 `+` 来实现两个字符串的拼接: ```python greeting = "Hello" name = "Alice" message = greeting + ", " + name # 输出: Hello, Alice ``` ##### 分割字符串 使用 `split()` 函数可以根据指定分隔符将字符串分割成列表: ```python text = "apple,banana,cherry" fruits = text.split(",") # ['apple', 'banana', 'cherry'] ``` ##### 查找子串位置 利用 `find()` 或者 `index()` 可以找到某个子串首次出现的位置;如果找不到,则 `find()` 返回 `-1` 而 `index()` 抛出异常: ```python sentence = "Welcome to the jungle." position_find = sentence.find("jungle") # position_find=11 try: position_index = sentence.index("desert") except ValueError as e: print(e) # substring not found ``` ##### 替换子串 通过 `replace(old, new)` 将旧子串替换成新子串: ```python old_text = "I like cats and dogs." new_text = old_text.replace("cats", "rabbits") # I like rabbits and dogs. ``` ##### 大小写转换 支持多种大小写的转换方式,比如全部大写、首字母大写等: ```python lowercase = "hello".upper() # HELLO uppercase = "WORLD".lower() # world capitalized = "john doe".capitalize() # John doe titlecased = "john DOE".title() # John Doe ``` #### 特殊字符处理 ##### 去除空白字符 为了去除字符串两端多余的空格或其他空白字符,可以采用 `strip()` 方法。此方法会移除开头和结尾处所有的空白字符(包括空格、制表符 `\t` 和换行符 `\n`),但不会影响中间部分的任何空白字符[^2]。 ```python trimmed_string = ' hello there! '.strip() print(trimmed_string) # hello there! ``` #### 序列字符串 当有一个由多个项组成的序列并希望将其组合成单一字符串时,可借助于 `join()` 方法。该方法接收一个迭代器作为参数,并用给定的分隔符把各个元素连在一起形成一个新的字符串对象[^3]。 ```python words_list = ["Python", "is", "awesome"] joined_sentence = "-".join(words_list) print(joined_sentence) # Python-is-awesome ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值