Python |字符串操作

一、简单操作

\ 转义符

testimony = 'This shirt doesn\'t fit me'
words = 'hello \nshark'
In [38]: words                                                                                  
Out[38]: 'hello \nsharl'

In [39]: print(words)                                                                           
hello 
sharl

+拼接

>>> s1 = "lenovo"
>>> s2 = 'good'
>>> s = s1 + " " +  s2 + "\n"
>>> s
'lenovo good\n'
>>> print(s)
lenovo good
>>>

不可以用 字符串和 一个非字符串类型的对象相加

'lenovo' + 1   # 这会报错的

*** 复制**

>>> print('*' * 10)
**********
>>> print('lenovo 666 -->\n' * 6)
lenovo 666 -->
lenovo 666 -->
lenovo 666 -->
lenovo 666 -->
lenovo 666 -->
lenovo 666 -->
>>>

二、进阶操作

字符串 是 Python 中的一个 序列类型 的数据结构
存放的数据,在其内是有序的,内部的数据是可以通过在其
内部所处的位置进行访问等操作。
序列类型的特点:
序列里的每个数据被称为序列的一个元素
元素在序列里都是有个自己的位置的,这个位置被称为索引或者叫偏移量,也有叫下标的,下标索号好从 0 开始的。
序列中的每一个元素可以通过这个元素的索引号来获取到
获取序列类型数据中的多个元素需要用切片的操作来获取到

s1 = "shark"
# 使用切片获取多个元素
>>> s1[0:2]
'le'
# 起始和结尾的索引号可以不写
>>> s1 = "lenovo"
>>> s1[:]
'lenovo'
>>> s1[4:]
'vo'
>>> s1[:-1]
'lenov'
>>>

下面这样的操作,臣妾做不到

>>> s1[-1:-3]
''
>>>

因为从左向右开始操作, 索引号 -1 的右边没有任何索引号了
-3 在 -1 的左边

# 获取字符串的长度,包含空格和换行符
>>> n = len(s1)
>>> n
6
>>>

利用字符串对象的方法
split 分割
默认使用 空格或者 Tab 间做为分隔符

>>> url = '淘宝官网  www.taobao.tom'
>>> url.split()
['淘宝官网,www.taobao.com']

可以指定分隔符

>>> ip = '192.168.1.100'
>>> ip.split('.')
['192', '168', '1', '100']
rsplit 从右向左分割

>>> ip.rsplit('.', 1)
['192.168.1', '100']
>>>

上面 split('.', 1) 中的第二参数 1 ,表示 找到第一个分隔符 .,就结束。

replace 替换

>>> url = 'www.qfedu.com'
>>> url2 = url.replace('.', '_')
>>> url
'www.qfedu.com'
>>> url2
'www_qfedu_com'

strip 移除字符串两端的空白字符

>>> s = ' shark '
>>> s
' shark '
>>> s.strip()
'shark'
>>>

startswith 判断字符串以什么为开头

>>> s = 'lenovo'
>>> s.startswith('l')
True
>>> s.startswith('le')
True

endswith 判断字符串以什么为结尾

>>> s.endswith('o')
True
>>> s.endswith('vo')
True
>>>

三、交互输入

>>> inp = input("请输入:")
请输入:shark
>>> inp
'shark '
>>> inp.strip()
'shark'
>>> inp = inp.strip()
>>> inp
'shark'
>>> inp = input("请输入:")  # 'shark '
KeyboardInterrupt
>>> inp = 'shark '
KeyboardInterrupt
>>> 'shark '.strip()
'shark'
>>> inp = 'shark '.strip()
>>> inp
'shark'
>>> inp = input("请输入:").strip()
请输入:shark
>>> inp
'shark'
>>>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值