2022年有哪些Python字符串操作技巧值得收藏学习?

2026-05-28 18:002阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计3530个文字,预计阅读时间需要15分钟。

2022年有哪些Python字符串操作技巧值得收藏学习?

《重新定义原创版权:探索数字时代的版权保护边界》https://www.gewuweb.com/hot/17228.

尊重原创版权: <www.gewuweb.com/hot/17228.html>

# 精心整理了100+Python字符串常用操作,收藏备用

字符串作为平时使用最多的数据类型,其常用的操作我们还是很有必要熟记于心的,本文整理了多种字符串的操作的案例,还是非常用心, **

全文篇幅巨长,建议收藏再看 **


![精心整理了100+Python字符串常用操作,收藏备用](p26.toutiaoimg.com/origin/tos-cn-i-qvj2lq49k0/ffdcb111dd6647fb81463b118457ce73?from=pc)


* 字符串切片操作

* 检查字符串是否为空

* 计算字符串中字符出现次数的多种方法

* 将 String 变量转换为 float、int 或 boolean

* 向字符串填充或添加零的不同方法

* 去掉字符串中的 space 字符

* 生成N个字符的随机字符串

* 以不同的方式反转字符串

* 将 Camel Case 转换为 Snake Case 并更改给定字符串中特定字符的大小写

* 检查给定的字符串是否是 Python 中的回文字符串

* 检查字符串是否以列表中的一个字符串结尾

* 在字符串中应用查找模式

* 如果是 Python 中的反斜杠,则删除最后一个字符

* 在Python中拆分字符串而不丢失拆分字符

* 从字符串 Python 中提取大写和小写字符

* 如何在 Python 中比较字符串的索引是否相等

* 在每个第 4 个字符上添加空格

* 在 Python 中以多行方式连接字符串

* 在 Python 中将多个变量附加到列表中

* 将字符串拆分为 Python 中的字符列表

* 如何在 Python 中小写字符串

* 通过多个标点符号分割字符串

* Python 字符串填充

* 在 Python 中检查两个字符串是否包含相同的字符

* 在 Python 中查找给定字符串中的整个单词

* 查找所有出现的子字符串

* 在 Python 中去除所有开头在Python中的正斜杠上拆分字符串和结尾标点符号

* 用 Python 中的正斜杠上拆分字符串

* 根据 Python 中的索引位置将字符串大写

* 检查字符串中的所有字符是否都是Python中的数字

* 为什么使用'=='或'is'比较字符串有时会产生不同的结果

* 如何在 Python 中为字符串添加 X 个空格

* 如何在Python中替换字符串中的特定字符串实例

* 如何连接两个变量,一个是字符串,另一个是 Python 中的 int

* 在 Python 中的反斜杠上拆分字符串

* 在Python中随机大写字符串中的字母

* 在单词处拆分字符串并且或不保留分隔符

* 在 Python 中填充 n 个字符

* 检查变量是否等于一个字符串或另一个字符串

* Python字符串格式化固定宽度

* 在Python中查找字符串中字符的所有位置

* 在Python中从左右修剪指定数量的空格

* 在Python中按字符串中字符的位置拆分字符串

* 将Python字符串中的第一个和最后一个字母大写

* 检查字符串是否以Python中的给定字符串或字符结尾

* 如何在 Python 中比较两个字符串

* 在Python中将整数格式化为带有前导零的字符串

* 在Python中替换字符串的多个子字符串

* Python字符串替换字符

* 在Python中查找字符串中所有出现的单词的所有索引

* 在 Python 中将字符串中每个单词的首字母大写

* 仅在 Python 中的双引号后拆分字符串

* 在 Python 中以字节为单位获取字符串的大小

* 在 Python 中比较字符串中的字符

* 在 Python 中的括号和字符串之间添加空格

* 在 Python 中删除开头和结尾空格

* 在 Python 中拆分字符串以获得第一个值

* 在 Python 中检查字符串是大写、小写还是混合大小写

* Python计数字符串出现在给定字符串中

* 在 Python3 中用前导零填充字符串

* 在 Python 中检查两个字符串是否包含相同的字母和数字

* 在Python中的字符串中的字符之间添加空格的有效方法

* 在Python中查找字符串中最后一次出现的子字符串的索引

* 在 Python 中将字符串大写

* 拆分非字母数字并在 Python 中保留分隔符

* 计算Python中字符串中大写和小写字符的数量

* 在 Python 中将字符串与枚举进行比较

* Python中的段落格式

* 从 Python 中的某个索引替换字符

* 如何连接 str 和 int 对象

* 仅在 Python 中将字符串拆分为两部分

* 将大写字符串转换为句子大小写

* 在标点符号上拆分字符串

* 在 Python 中比较字符串

* 用零填充数字字符串

* 找到两个字符串之间的差异位置

* Python填充字符串到固定长度

* Python中的字符串查找示例

* 删除字符串中的开头零和结尾零

* Python在换行符上拆分

* 将字符串中的每个第二个字母大写

* 在 Python 中查找一个月的最后一个营业日或工作日

* 比较两个字符串中的单个字符

* 在 Python 中多次显示字符串

* Python 从头开始替换字符串

* 在 Python 中连接字符串和变量值

* 在每个下划线处拆分字符串并在第 N 个位置后停止

* Python 中列表中第一个单词的首字母大写

* 如何在 Python 字符串中找到第一次出现的子字符串

* 不同长度的 Python 填充字符串

* Python 比较两个字符串保留一端的差异

* 如何用 Python 中的一个字符替换字符串中的所有字符

* 在字符串中查找子字符串并在 Python 中返回子字符串的索引

* 从 Python 中的字符串中修剪特定的开头和结尾字符

* 在 Python 中按长度将字符串拆分为字符串

* 如何在 Python 中将字符串的第三个字母大写

* 将制表符大小设置为指定的空格数

* 将两个字符串与某些字符进行比较

* 字符串格式化填充负数

* 单独替换字符串中的第一个字符

* 连接固定字符串和变量

* 将字符串拆分为多个字符串

* 在 Python 中将字符串大写

* 将字节字符串拆分为单独的字节

* 用空格填写 Python 字符串

* 比较两个字符串并检查它们共有多少个字符

* 在 Python 中的数字和字符串之间添加空格

* 如何在 Python 中去除空格

* 字符串中最后一次出现的分隔符处拆分字符串

* 在Python中将字符串的最后一个字母大写

* 使用指定字符居中对齐字符串

* 格式字符串中动态计算的零填充

* 在 Python 中使用 string.replace()

* 在 Python 中获取字符的位置

* Python字符串替换多次出现

* 在索引后找到第一次出现的字符

* 在 Python 中将字符串更改为大写

* 在 Python 中拆分具有多个分隔符的字符串

* 在 Python 中获取字符串的大小

* Python中的字符串比较 is vs ==

* 每当数字与非数字相邻时,Python 正则表达式都会添加空格

* 在 Python 中仅按第一个空格拆分字符串

* 在Python中将字符串中的一些小写字母更改为大写

* 将字符串拆分为具有多个单词边界分隔符的单词

* 检查一个字符串在 Python 中是否具有相同的字符

* 在多个分隔符或指定字符上拆分字符串

* 将一个字符串附加到另一个字符串

* 在 Python 中遍历字符串

* 从 Python 中的字符串中去除标点符号

* 将列表转换为字符串

* 将 JSON 转换为字符串

* 对字符串列表进行排序

* 在 Python 中检查字符串是否以 XXXX 开头

* 在 Python 中将两个字符串网格或交错在一起的不同方法

# 字符串切片操作



test = "Python Programming"

print("String: ", test)


# First one character

first_character = test[:1]

print("First Character: ", first_character)


# Last one character

last_character = test[-1:]

print("Last Character: ", last_character)


# Everything except the first one character

except_first = test[1:]

print("Except First Char.: ", except_first)


# Everything except the last one character

except_last = test[:-1]

print("Except First Char.: ", except_last)


# Everything between first and last two character

between_two = test[2:-2]

print("Between two character: ", between_two)


# Skip one character

skip_one = test[0:18:2] # [start:stop:step]

print("Skip one character: ", skip_one)


# Reverse String

reverse_str = test[::-1]

print("Reverse String: ", reverse_str)


Output:



String: Python Programming


First Character: P


Last Character: g


Except First Char.: ython Programming


Except First Char.: Python Programmin


Between two character: thon Programmi


Skip one character: Pto rgamn


Reverse String: gnimmargorP nohtyP


# 检查字符串是否为空



import re

from collections import Counter


sentence = 'Canada is located in the northern part of North America'

# Example I

counter = len(re.findall("a", sentence))

print(counter)


# Example II

counter = sentence.count('a')

print(counter)


# Example III

counter = Counter(sentence)

print(counter['a'])


Output:



Empty


Empty


Empty


# 计算字符串中字符出现次数的多种方法



import re

from collections import Counter


sentence = 'Canada is located in the northern part of North America'

# Example I

counter = len(re.findall("a", sentence))

print(counter)


# Example II

counter = sentence.count('a')

print(counter)


# Example III

counter = Counter(sentence)

print(counter['a'])


Output:

# 将 String 变量转换为 float、int 或 boolean



# String to Float

float_string = "254.2511"

print(type(float_string))


string_to_float = float(float_string)

print(type(string_to_float))


# String to Integer

int_string = "254"

print(type(int_string))


string_to_int = int(int_string)

print(type(string_to_int))



# String to Boolean

bool_string = "True"

print(type(bool_string))


string_to_bool = bool(bool_string)

print(type(string_to_bool))


Output:



class 'str'


class 'float>


class 'str'


class 'int'


class 'str'


class 'bool'


# 向字符串填充或添加零的不同方法



num = 7


print('{0:0>5d}'.format(num)) # left

print('{0:0<5d}'.format(num)) # right


print('{:05d}'.format(num))


print("%0*d" % (5, num))

print(format(num, "05d"))


temp = 'test'

print(temp.rjust(10, '0'))

print(temp.ljust(10, '0'))


Output:



00007


70000


00007


00007


00007


000000test


test000000


# 去掉字符串中的 space 字符



string_var = " \t a string example\n\t\r "

print(string_var)


string_var = string_var.lstrip() # trim white space from left

print(string_var)


string_var = " \t a string example\t "

string_var = string_var.rstrip() # trim white space from right

print(string_var)

2022年有哪些Python字符串操作技巧值得收藏学习?


string_var = " \t a string example\t "

string_var = string_var.strip() # trim white space from both side

print(string_var)


Output:



a string example






a string example






a string example


a string example


# 生成N个字符的随机字符串



import string

import random



def string_generator(size):

chars = string.ascii_uppercase + string.ascii_lowercase

return ''.join(random.choice(chars) for _ in range(size))



def string_num_generator(size):

chars = string.ascii_lowercase + string.digits

return ''.join(random.choice(chars) for _ in range(size))



# Random String

test = string_generator(10)

print(test)


# Random String and Number

test = string_num_generator(15)

print(test)


Output:



acpPTojXet


qmpah72cjb83eqd


# 以不同的方式反转字符串



test_string = 'Python Programming'


string_reversed = test_string[-1::-1]

print(string_reversed)


string_reversed = test_string[::-1]

print(string_reversed)



# String reverse logically

def string_reverse(text):

r_text = ''

index = len(text) - 1


while index >= 0:

r_text += text[index]

index -= 1


return r_text


print(string_reverse(test_string))


Output:



gnimmargorP nohtyP


gnimmargorP nohtyP


gnimmargorP nohtyP


# 将 Camel Case 转换为 Snake Case 并更改给定字符串中特定字符的大小写



import re



def convert(oldstring):

s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', oldstring)

return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()



# Camel Case to Snake Case

print(convert('CamelCase'))

print(convert('CamelCamelCase'))

print(convert('getHTTPResponseCode'))

print(convert('get2HTTPResponseCode'))


# Change Case of a particular character

text = "python programming"

result = text[:1].upper() + text[1:7].lower() \

+ text[7:8].upper() + text[8:].lower()

print(result)


text = "Kilometer"

print(text.lower())


old_string = "hello python"

new_string = old_string.capitalize()

print(new_string)


old_string = "Hello Python"

new_string = old_string.swapcase()

print(new_string)


Output:



camel_case


camel_camel_case


get_www.gewuweb.com/sitemap.html>

本文共计3530个文字,预计阅读时间需要15分钟。

2022年有哪些Python字符串操作技巧值得收藏学习?

《重新定义原创版权:探索数字时代的版权保护边界》https://www.gewuweb.com/hot/17228.

尊重原创版权: <www.gewuweb.com/hot/17228.html>

# 精心整理了100+Python字符串常用操作,收藏备用

字符串作为平时使用最多的数据类型,其常用的操作我们还是很有必要熟记于心的,本文整理了多种字符串的操作的案例,还是非常用心, **

全文篇幅巨长,建议收藏再看 **


![精心整理了100+Python字符串常用操作,收藏备用](p26.toutiaoimg.com/origin/tos-cn-i-qvj2lq49k0/ffdcb111dd6647fb81463b118457ce73?from=pc)


* 字符串切片操作

* 检查字符串是否为空

* 计算字符串中字符出现次数的多种方法

* 将 String 变量转换为 float、int 或 boolean

* 向字符串填充或添加零的不同方法

* 去掉字符串中的 space 字符

* 生成N个字符的随机字符串

* 以不同的方式反转字符串

* 将 Camel Case 转换为 Snake Case 并更改给定字符串中特定字符的大小写

* 检查给定的字符串是否是 Python 中的回文字符串

* 检查字符串是否以列表中的一个字符串结尾

* 在字符串中应用查找模式

* 如果是 Python 中的反斜杠,则删除最后一个字符

* 在Python中拆分字符串而不丢失拆分字符

* 从字符串 Python 中提取大写和小写字符

* 如何在 Python 中比较字符串的索引是否相等

* 在每个第 4 个字符上添加空格

* 在 Python 中以多行方式连接字符串

* 在 Python 中将多个变量附加到列表中

* 将字符串拆分为 Python 中的字符列表

* 如何在 Python 中小写字符串

* 通过多个标点符号分割字符串

* Python 字符串填充

* 在 Python 中检查两个字符串是否包含相同的字符

* 在 Python 中查找给定字符串中的整个单词

* 查找所有出现的子字符串

* 在 Python 中去除所有开头在Python中的正斜杠上拆分字符串和结尾标点符号

* 用 Python 中的正斜杠上拆分字符串

* 根据 Python 中的索引位置将字符串大写

* 检查字符串中的所有字符是否都是Python中的数字

* 为什么使用'=='或'is'比较字符串有时会产生不同的结果

* 如何在 Python 中为字符串添加 X 个空格

* 如何在Python中替换字符串中的特定字符串实例

* 如何连接两个变量,一个是字符串,另一个是 Python 中的 int

* 在 Python 中的反斜杠上拆分字符串

* 在Python中随机大写字符串中的字母

* 在单词处拆分字符串并且或不保留分隔符

* 在 Python 中填充 n 个字符

* 检查变量是否等于一个字符串或另一个字符串

* Python字符串格式化固定宽度

* 在Python中查找字符串中字符的所有位置

* 在Python中从左右修剪指定数量的空格

* 在Python中按字符串中字符的位置拆分字符串

* 将Python字符串中的第一个和最后一个字母大写

* 检查字符串是否以Python中的给定字符串或字符结尾

* 如何在 Python 中比较两个字符串

* 在Python中将整数格式化为带有前导零的字符串

* 在Python中替换字符串的多个子字符串

* Python字符串替换字符

* 在Python中查找字符串中所有出现的单词的所有索引

* 在 Python 中将字符串中每个单词的首字母大写

* 仅在 Python 中的双引号后拆分字符串

* 在 Python 中以字节为单位获取字符串的大小

* 在 Python 中比较字符串中的字符

* 在 Python 中的括号和字符串之间添加空格

* 在 Python 中删除开头和结尾空格

* 在 Python 中拆分字符串以获得第一个值

* 在 Python 中检查字符串是大写、小写还是混合大小写

* Python计数字符串出现在给定字符串中

* 在 Python3 中用前导零填充字符串

* 在 Python 中检查两个字符串是否包含相同的字母和数字

* 在Python中的字符串中的字符之间添加空格的有效方法

* 在Python中查找字符串中最后一次出现的子字符串的索引

* 在 Python 中将字符串大写

* 拆分非字母数字并在 Python 中保留分隔符

* 计算Python中字符串中大写和小写字符的数量

* 在 Python 中将字符串与枚举进行比较

* Python中的段落格式

* 从 Python 中的某个索引替换字符

* 如何连接 str 和 int 对象

* 仅在 Python 中将字符串拆分为两部分

* 将大写字符串转换为句子大小写

* 在标点符号上拆分字符串

* 在 Python 中比较字符串

* 用零填充数字字符串

* 找到两个字符串之间的差异位置

* Python填充字符串到固定长度

* Python中的字符串查找示例

* 删除字符串中的开头零和结尾零

* Python在换行符上拆分

* 将字符串中的每个第二个字母大写

* 在 Python 中查找一个月的最后一个营业日或工作日

* 比较两个字符串中的单个字符

* 在 Python 中多次显示字符串

* Python 从头开始替换字符串

* 在 Python 中连接字符串和变量值

* 在每个下划线处拆分字符串并在第 N 个位置后停止

* Python 中列表中第一个单词的首字母大写

* 如何在 Python 字符串中找到第一次出现的子字符串

* 不同长度的 Python 填充字符串

* Python 比较两个字符串保留一端的差异

* 如何用 Python 中的一个字符替换字符串中的所有字符

* 在字符串中查找子字符串并在 Python 中返回子字符串的索引

* 从 Python 中的字符串中修剪特定的开头和结尾字符

* 在 Python 中按长度将字符串拆分为字符串

* 如何在 Python 中将字符串的第三个字母大写

* 将制表符大小设置为指定的空格数

* 将两个字符串与某些字符进行比较

* 字符串格式化填充负数

* 单独替换字符串中的第一个字符

* 连接固定字符串和变量

* 将字符串拆分为多个字符串

* 在 Python 中将字符串大写

* 将字节字符串拆分为单独的字节

* 用空格填写 Python 字符串

* 比较两个字符串并检查它们共有多少个字符

* 在 Python 中的数字和字符串之间添加空格

* 如何在 Python 中去除空格

* 字符串中最后一次出现的分隔符处拆分字符串

* 在Python中将字符串的最后一个字母大写

* 使用指定字符居中对齐字符串

* 格式字符串中动态计算的零填充

* 在 Python 中使用 string.replace()

* 在 Python 中获取字符的位置

* Python字符串替换多次出现

* 在索引后找到第一次出现的字符

* 在 Python 中将字符串更改为大写

* 在 Python 中拆分具有多个分隔符的字符串

* 在 Python 中获取字符串的大小

* Python中的字符串比较 is vs ==

* 每当数字与非数字相邻时,Python 正则表达式都会添加空格

* 在 Python 中仅按第一个空格拆分字符串

* 在Python中将字符串中的一些小写字母更改为大写

* 将字符串拆分为具有多个单词边界分隔符的单词

* 检查一个字符串在 Python 中是否具有相同的字符

* 在多个分隔符或指定字符上拆分字符串

* 将一个字符串附加到另一个字符串

* 在 Python 中遍历字符串

* 从 Python 中的字符串中去除标点符号

* 将列表转换为字符串

* 将 JSON 转换为字符串

* 对字符串列表进行排序

* 在 Python 中检查字符串是否以 XXXX 开头

* 在 Python 中将两个字符串网格或交错在一起的不同方法

# 字符串切片操作



test = "Python Programming"

print("String: ", test)


# First one character

first_character = test[:1]

print("First Character: ", first_character)


# Last one character

last_character = test[-1:]

print("Last Character: ", last_character)


# Everything except the first one character

except_first = test[1:]

print("Except First Char.: ", except_first)


# Everything except the last one character

except_last = test[:-1]

print("Except First Char.: ", except_last)


# Everything between first and last two character

between_two = test[2:-2]

print("Between two character: ", between_two)


# Skip one character

skip_one = test[0:18:2] # [start:stop:step]

print("Skip one character: ", skip_one)


# Reverse String

reverse_str = test[::-1]

print("Reverse String: ", reverse_str)


Output:



String: Python Programming


First Character: P


Last Character: g


Except First Char.: ython Programming


Except First Char.: Python Programmin


Between two character: thon Programmi


Skip one character: Pto rgamn


Reverse String: gnimmargorP nohtyP


# 检查字符串是否为空



import re

from collections import Counter


sentence = 'Canada is located in the northern part of North America'

# Example I

counter = len(re.findall("a", sentence))

print(counter)


# Example II

counter = sentence.count('a')

print(counter)


# Example III

counter = Counter(sentence)

print(counter['a'])


Output:



Empty


Empty


Empty


# 计算字符串中字符出现次数的多种方法



import re

from collections import Counter


sentence = 'Canada is located in the northern part of North America'

# Example I

counter = len(re.findall("a", sentence))

print(counter)


# Example II

counter = sentence.count('a')

print(counter)


# Example III

counter = Counter(sentence)

print(counter['a'])


Output:

# 将 String 变量转换为 float、int 或 boolean



# String to Float

float_string = "254.2511"

print(type(float_string))


string_to_float = float(float_string)

print(type(string_to_float))


# String to Integer

int_string = "254"

print(type(int_string))


string_to_int = int(int_string)

print(type(string_to_int))



# String to Boolean

bool_string = "True"

print(type(bool_string))


string_to_bool = bool(bool_string)

print(type(string_to_bool))


Output:



class 'str'


class 'float>


class 'str'


class 'int'


class 'str'


class 'bool'


# 向字符串填充或添加零的不同方法



num = 7


print('{0:0>5d}'.format(num)) # left

print('{0:0<5d}'.format(num)) # right


print('{:05d}'.format(num))


print("%0*d" % (5, num))

print(format(num, "05d"))


temp = 'test'

print(temp.rjust(10, '0'))

print(temp.ljust(10, '0'))


Output:



00007


70000


00007


00007


00007


000000test


test000000


# 去掉字符串中的 space 字符



string_var = " \t a string example\n\t\r "

print(string_var)


string_var = string_var.lstrip() # trim white space from left

print(string_var)


string_var = " \t a string example\t "

string_var = string_var.rstrip() # trim white space from right

print(string_var)

2022年有哪些Python字符串操作技巧值得收藏学习?


string_var = " \t a string example\t "

string_var = string_var.strip() # trim white space from both side

print(string_var)


Output:



a string example






a string example






a string example


a string example


# 生成N个字符的随机字符串



import string

import random



def string_generator(size):

chars = string.ascii_uppercase + string.ascii_lowercase

return ''.join(random.choice(chars) for _ in range(size))



def string_num_generator(size):

chars = string.ascii_lowercase + string.digits

return ''.join(random.choice(chars) for _ in range(size))



# Random String

test = string_generator(10)

print(test)


# Random String and Number

test = string_num_generator(15)

print(test)


Output:



acpPTojXet


qmpah72cjb83eqd


# 以不同的方式反转字符串



test_string = 'Python Programming'


string_reversed = test_string[-1::-1]

print(string_reversed)


string_reversed = test_string[::-1]

print(string_reversed)



# String reverse logically

def string_reverse(text):

r_text = ''

index = len(text) - 1


while index >= 0:

r_text += text[index]

index -= 1


return r_text


print(string_reverse(test_string))


Output:



gnimmargorP nohtyP


gnimmargorP nohtyP


gnimmargorP nohtyP


# 将 Camel Case 转换为 Snake Case 并更改给定字符串中特定字符的大小写



import re



def convert(oldstring):

s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', oldstring)

return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()



# Camel Case to Snake Case

print(convert('CamelCase'))

print(convert('CamelCamelCase'))

print(convert('getHTTPResponseCode'))

print(convert('get2HTTPResponseCode'))


# Change Case of a particular character

text = "python programming"

result = text[:1].upper() + text[1:7].lower() \

+ text[7:8].upper() + text[8:].lower()

print(result)


text = "Kilometer"

print(text.lower())


old_string = "hello python"

new_string = old_string.capitalize()

print(new_string)


old_string = "Hello Python"

new_string = old_string.swapcase()

print(new_string)


Output:



camel_case


camel_camel_case


get_www.gewuweb.com/sitemap.html>