python字符串的10个常用方法总结

文章目录

  • 1 字符串用 + 和 * 连接
  • 2 len(string)——计算字符串的长度
  • 3 string[left,right]——字符串的分片与索引
  • 4 string.find(sub_string)——查找子字符串出现的位置
  • 5 string.replace(string_a,string_b)——替换部分字符串
  • 6 str(int_a)——强制类型转换
  • 7 '{} and {}'.format(string_a,string_b)——字符串格式化符
  • 8 strings.split()——分割字符串中的单词
  • 9 strings.count(string)——统计字符string出现的次数
  • 10 strings.strip(string.punctuation).lower()——忽略字符,转换小写

1 字符串用 + 和 * 连接

+连接

what_he_does = ' plays '
his_instrument = 'guitar'
his_name = 'Robert Johnson'
artist_intro = his_name + what_he_does + his_instrument
print(artist_intro)

# echo
Robert Johnson plays guitar

*连接

word = 'love'
words = word*3
print(words)

# echo
lovelovelove

2 len(string)——计算字符串的长度

word = 'love'
words = word*3
print(len(words))

# echo
12

3 string[left,right]——字符串的分片与索引

字符串有点像一个元组,所以可以用string[index]的方式进行索引

print(name[5:])			# 右侧不写,代表到最后
'me is Mike'
print(name[:5])			# 注意是左闭右开,所以第5个是取不到的
'My na'

从左到右,是和数组一样,从0开始的,而从右往左是从-1开始,具体索引方式如下

python字符串的10个常用方法总结_第1张图片

4 string.find(sub_string)——查找子字符串出现的位置

sub_num = '123'
phone_num = '138-1034-5123'
print(phone_num.find(sub_num))

# echo
10									# 返回第一次出现123这个字符串的位置,10是1的位置

5 string.replace(string_a,string_b)——替换部分字符串

phone_num = '138-1034-5123'
phone_num_new = phone_num.replace(phone_num[9:13],'*'*4)
print(phone_num_new)

# echo
138-1034-****

6 str(int_a)——强制类型转换

sub_num = '123'
phone_num = '138-1034-5123'
# 用type()函数确定变量类型
print(phone_num.find(sub_num),type(phone_num.find(sub_num)))
print(str(phone_num.find(sub_num)),type(str(phone_num.find(sub_num))))

# echo
10 <class 'int'>			# find()返回的是int类型
10 <class 'str'>			# str()强制转换成string字符串类型

7 ‘{} and {}’.format(string_a,string_b)——字符串格式化符

a = 'I'
b = 'you'
print('{} love {} forever.'.format(a,b))

# echo
I love you forever.

8 strings.split()——分割字符串中的单词

lyric = 'The night begin to shine, the night begin to shine'
words = lyric.split()
print(words)

# echo
['The', 'night', 'begin', 'to', 'shine,', 'the', 'night', 'begin', 'to', 'shine']		# 注意:'shine,'后面跟了一个逗号!

默认split()是根据空格划分的,可以使用split('\n')根据换行来分割

fn.append(line.split('\n')[0])	# [0]表示分割后list的第一个元素

9 strings.count(string)——统计字符string出现的次数

lyric = 'The night begin to shine, the night begin to shine'
words = lyric.split()
word = 'night'
print(words.count(word))

# echo
2							# 'night'出现了两次

10 strings.strip(string.punctuation).lower()——忽略字符,转换小写

string.punctuation包含以下的特殊字符:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

使用strip(ch)可以忽略ch这些字符

string.lower()可以将字符串全部转换成小写。

import string
lyric = 'The night begin to shine, the night begin to shine'
# 首先把字符串按照空格分开,切割成包含一个个string的list
# 接着使用列表解析式,对每个元素进行1)忽略特殊字符2)转换成小写单词
words = [word.strip(string.punctuation).lower() for word in lyric.split()]
print(words)

# echo
['the', 'night', 'begin', 'to', 'shine', 'the', 'night', 'begin', 'to', 'shine']

你可能感兴趣的:(Python学习)