python字符串基础操作

Python中可以使用一对单引号''或者双引号""生成字符串。

分割
s.split()将s按照空格(包括多个空格,制表符\t,换行符\n等)分割,并返回所有分割得到的字符串。
input:

line = "1 2 3 4  5"
numbers = line.split()
print (numbers)

output:
['1', '2', '3', '4', '5']

s.split(sep)以给定的sep为分隔符对s进行分割。
input:

line = "1,2,3,4,5"
numbers = line.split(',')
print (numbers)

output:
['1', '2', '3', '4', '5']

连接
与分割相反,s.join(str_sequence)的作用是以s为连接符将字符串序列str_sequence中的元素连接起来,并返回连接后得到的新字符串:

input:

s = ' '
s.join(numbers)

output:
'1 2 3 4 5'

input:

s = ','
s.join(numbers)

output:
'1,2,3,4,5'

替换
s.replace(part1, part2)将字符串s中指定的部分part1替换成想要的部分part2,并返回新的字符串。
input:

s = "hello world"
s.replace('world', 'python')

output:
'hello python'

此时,s的值并没有变化,替换方法只是生成了一个新的字符串。
input:
print(s)
output:
'hello world'

大小写转换
s.upper()方法返回一个将s中的字母全部大写的新字符串。
s.lower()方法返回一个将s中的字母全部小写的新字符串。
input:
"hello world".upper()
output:
'HELLO WORLD'


这两种方法也不会改变原来s的值:
input:

s = "HELLO WORLD"
print (s.lower())
print (s)

output:

hello world
HELLO WORLD

去除多余空格
s.strip()返回一个将s两端的多余空格除去的新字符串。
s.lstrip()返回一个将s开头的多余空格除去的新字符串。
s.rstrip()返回一个将s结尾的多余空格除去的新字符串。
input:

s = "  hello world   "
s.strip()

output:
'hello world'
s的值依然不会变化

更多方法
可以使用dir函数查看所有可以使用的方法:
input:
dir(s)


多行字符串
Python 用一对 """ 或者 ''' 来生成多行字符串:
input:

a = """hello world.
it is a nice day."""
print (a)

output:

hello world.
it is a nice day.

强制转换为字符串
str(ob)强制将ob转化成字符串。
repr(ob)也是强制将ob转化成字符串。

整数与不同进制的字符串的转化
可以将整数按照不同进制转化为不同类型的字符串。
可以指定按照多少进制来进行转换,最后返回十进制表达的整数:
input:
int('377', 8)
output:
255

索引
对于一个有序序列,可以通过索引的方法来访问对应位置的值。字符串便是一个有序序列,Python 使用 下标 来对有序序列进行索引。索引是从 0 开始的,所以索引 0 对应与序列的第 1 个元素。
input:

s = "hello world"
s[0]

output:
'h'
Python中索引是从 0 开始的,所以索引 0 对应与序列的第 1 个元素。为了得到第 5 个元素,需要使用索引值 4 。


除了正向索引,Python还引入了负索引值的用法,即从后向前开始计数,例如,索引 -2 表示倒数第 2 个元素:
input:
s[-2]
output:
'l'

分片
分片用来从序列中提取出想要的子序列,其用法为:
var[lower:upper:step]
input:
s[1:3]
output:
'el'
分片中包含的元素的个数为 3-1=2 。也可以使用负索引来指定分片的范围,区间为左闭右开。
lower和upper可以省略,省略lower意味着从开头开始分片,省略upper意味着一直分片到结尾。
input:
s[:3]
output:
'hel'

每隔两个取一个值:
input:
s[::2]
output:
'hlowrd'
当step的值为负时,省略lower意味着从结尾开始分片,省略upper意味着一直分片到开头。
input:
s[::-1]
output:
'dlrow olleh'

posted @ 2022-05-27 15:49  AzathothLXL  阅读(158)  评论(0)    收藏  举报