python string 详解

简介: python string 详解

文章目录

字符串截取

#!/usr/bin/python
#---utf-8---
temp="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#访问单个元素
print(temp[0]) #A
print(temp[-1]) #Z
#普通切片操作
print(temp[0:10])   #ABCDEFGHIJ
#隔着取
print(temp[0:10:2])    #ACEGI
#输出从第一个到倒数第N个数
print(temp[0:-2])     #ABCDEFGHIJKLMNOPQRSTUVWX
print(temp[:-2])    #ABCDEFGHIJKLMNOPQRSTUVWX
print(temp[-2:])     #YZ
#逆序输出
print(temp[::-1])    #ZYXWVUTSRQPONMLKJIHGFEDCBA
#循环迭代输出
for s in temp:
    print(s,end=' ' )    #A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 

字符串去空格

内置方法

  • lstrip:删除左边的空格

这个字符串方法,会删除字符串s开始位置前的空格。

>>> s.lstrip()
'string   '
  • rstrip:删除右连的空格

这个内置方法可以删除字符串末尾的所有空格,看下面演示代码:

>>> s.rstrip()
'    string'
  • strip:删除两端的空格

有的时候我们读取文件中的内容,每行2边都有空格,能不能一次性全部去掉呢,字符符有一个内置的strip()方法可以做到。

>>> s = “   这是一个字符串    ”
>>> s.strip()
'string'

一般方法

  • 使用字符串函数replace
>>> a = 'hello world'
>>> a.replace(' ', '')
'helloworld'
  • 使用字符串函数split
>>> a = ''.join(a.split())
>>> print(a)
helloworld
  • 使用正则表达式
>>> import re
>>> strinfo = re.compile()
>>> strinfo = re.compile(' ')
>>> b = strinfo.sub('', a)
>>> print(b)
helloworld

字符串转列表

参考链接:

相关文章
|
3月前
|
Python
python中split_string和substring区别
python中split_string和substring区别
54 1
|
18天前
|
XML 编解码 数据格式
Python标准数据类型-String(字符串)
Python标准数据类型-String(字符串)
23 2
|
1月前
|
安全 Python
Python系列(16)—— string类型转float类型
Python系列(16)—— string类型转float类型
|
1月前
|
Python
Python系列(15)—— int类型转string类型
Python系列(15)—— int类型转string类型
|
3月前
|
机器学习/深度学习 监控 安全
Python3.12 新版本之f-string的几个新特性
Python3.12 新版本之f-string的几个新特性
44 0
|
3月前
|
Python
python中split_string函数使用
python中split_string函数使用
24 0
|
4月前
|
移动开发 索引 Python
|
4月前
|
移动开发 前端开发 Shell
Python(十)python字符串String(2)
Python的字符串还是很有意思的。 之前在使用PHP的时候,拼接字符串是一件很简单的事。
42 0
|
4月前
|
Python
Python(十)python字符串String(1)
Python字符串使我们最常用的数据类型。 以使用引号( ' 或 " )来创建字符串。 一:创建字符串并访问他的值 # *定义字符串 *string_one = "我是一个字符串" print("string_one:" + string_one +",并且在打印的时候被更新了") 输出: string_one:我是一个字符串,并且在打印的时候被更新了 二:python的驻留机制 aa = 'python' bb = "python" cc = '''python''' print(id(aa)) print(id(bb)) print(id(cc)) 输出: 2307494144
40 0
|
7月前
|
Python
10 个 Python String 字符串的常用技巧,大大地提升我们的开发效率,终于有时间陪女朋友了
10 个 Python String 字符串的常用技巧,大大地提升我们的开发效率,终于有时间陪女朋友了

热门文章

最新文章