python 字符串特点

除了数值,Python可以操作字符串,它可以表现在以下几个方面。包含在单引号或双引号:

>>> 'spam eggs'
'spam eggs'
>>> 'doesn \' t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> " \" Yes, \" he said."
'"Yes," he said.'
>>> '"Isn \' t," she said.'
'"Isn \' t," she said.'

字符串可以写多行。可以用\n表示,下一行是一个合乎逻辑的延续行,最后一个字符用反斜杠:

hello = "This is a rather long string containing \n\
several lines of text just as you would do in C. \n\
   Note that whitespace at the beginning of the line is \
significant."

print hello

字符串可以被包围在一对三重引号里面:

print """
Usage: thingy [OPTIONS]
    -h                        Display this usage message
    -H hostname               Hostname to connect to
"""

字符串可以被连接在一起,用“+”运算符,重复*:

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word* 5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'

两个彼此相邻的字符串文字自动连接:

>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
 File "<stdin>", line 1, in ?
    'str'.strip() 'ing'
                     ^
SyntaxError: invalid syntax

注意:word字符串的内容是: “HelpA”  可以是下标(索引)和C一样,字符串的第一个字符下标(索引)0。可以指定的子串切片标志来表示:两个指数由冒号分隔。

>>> word[ 4]
'A'
>>> word[ 0: 2]
'He'
>>> word[ 2: 4]
'lp'

切片索引可以使用默认值;前一个索引默认为零,第二个索引默认被切片的字符串的大小。

>>> word[: 2]     # The first two characters
'He'
>>> word[ 2:]     # Everything except the first two characters
'lpA'

和C字符串不同,Python字符串不能改变。想修改指定索引位置的字符串会导致错误:

>>> word[ 0] = 'x'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn 't support item assignment
>>> word[: 1] = 'Splat'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn 't support slice assignment

然而,创建一个新的字符串是简单而有效的:

>>> 'x' + word[ 1:]
'xelpA'
>>> 'Splat' + word[ 4]
'SplatA'

这里是一个有用的切片操作:[:]+[:]等于。

>>> word[: 2] + word[ 2:]
'HelpA'
>>> word[: 3] + word[ 3:]
'HelpA'

指数可以是负数,从右边开始计数。例如:

>>> word[- 1]     # The last character
'A'
>>> word[- 2]     # The last-but-one character
'p'
>>> word[- 2:]     # The last two characters
'pA'
>>> word[:- 2]     # Everything except the last two characters
'Hel'
### Python去掉字符串中特定字符的方法 在Python中,可以通过多种方式去除字符串中的特定字符。以下是几种常见且高效的方式: #### 方法一:使用 `str.replace()` 替换单个或多个指定字符 `replace()` 是一种简单易用的字符串方法,可以用来替换目标字符为空字符串从而达到移除的效果。 ```python original_string = "hello cups world cup tablespoons {}" characters_to_remove = ["cups", "cup", "tablespoons", "{}"] result_string = original_string for char in characters_to_remove: result_string = result_string.replace(char, "") print(result_string) # 输出: hello world ``` 这种方法适用于少量的目标字符替代场景[^1]。 --- #### 方法二:利用列表解析与 `join()` 组合操作 通过遍历原始字符串并排除不需要的字符集合,最终重新组合成新的字符串。 ```python original_string = "hello cups world cup tablespoons {}" remove_set = set("".join(["cups", "cup", "tablespoons", "{}"])) filtered_characters = ''.join([char for char in original_string if char not in remove_set]) print(filtered_characters) # 输出: hello world ``` 此法适合当需要一次性处理大量单个字符的情况[^3]。 --- #### 方法三:借助正则表达式模块 `re` 对于复杂模式匹配需求(如连续词组),推荐采用正则表达式的解决方案。它可以灵活定义要删除的内容范围。 ```python import re original_string = "hello cups world cup tablespoons {}" pattern = r"(cups|cup|tablespoons|\{\})" cleaned_string = re.sub(pattern, "", original_string) print(cleaned_string.strip()) # 输出: hello world (注意中间多余的空格仍存在) ``` 这里需要注意的是,在实际应用过程中可能还需要额外调用 `.strip()` 或其他清理手段来进一步优化结果[^3]。 --- #### 特殊情况说明——去除首尾空白符 如果除了内部字符外还需考虑清除前后多余空间,则可结合以上任意一种技术再加上专门针对边缘空白区域的操作命令完成整个流程: ```python final_result = cleaned_string.strip() ``` 或者单独执行如下指令即可达成目的[^2]: ```python s = " 我们 " no_spaces_sides = s.strip() # 只去两头 only_left_removed = s.lstrip() # 左边清零 right_cleared = s.rstrip() # 删除右侧部分 ``` 综上所述,具体选用哪种策略取决于项目实际情况以及个人偏好等因素决定最佳实践方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值