周萝卜 萝卜大杂烩 - 精心整理了100+Python字符串常用操作

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

  • 字符串切片操作
  • 检查字符串是否为空
  • 计算字符串中字符出现次数的多种方法
  • 将 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 中将两个字符串网格或交错在一起的不同方法


    字符串切片操作

    ```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)

  1. <a name="osywo"></a>
  2. ### Output
  3. ```python
  4. String: Python Programming
  5. First Character: P
  6. Last Character: g
  7. Except First Char.: ython Programming
  8. Except First Char.: Python Programmin
  9. Between two character: thon Programmi
  10. Skip one character: Pto rgamn
  11. Reverse String: gnimmargorP nohtyP

检查字符串是否为空

  1. import re
  2. from collections import Counter
  3. sentence = 'Canada is located in the northern part of North America'
  4. # Example I
  5. counter = len(re.findall("a", sentence))
  6. print(counter)
  7. # Example II
  8. counter = sentence.count('a')
  9. print(counter)
  10. # Example III
  11. counter = Counter(sentence)
  12. print(counter['a'])

Output

  1. Empty
  2. Empty
  3. Empty

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

  1. import re
  2. from collections import Counter
  3. sentence = 'Canada is located in the northern part of North America'
  4. # Example I
  5. counter = len(re.findall("a", sentence))
  6. print(counter)
  7. # Example II
  8. counter = sentence.count('a')
  9. print(counter)
  10. # Example III
  11. counter = Counter(sentence)
  12. print(counter['a'])

Output

  1. 6
  2. 6
  3. 6

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

  1. # String to Float
  2. float_string = "254.2511"
  3. print(type(float_string))
  4. string_to_float = float(float_string)
  5. print(type(string_to_float))
  6. # String to Integer
  7. int_string = "254"
  8. print(type(int_string))
  9. string_to_int = int(int_string)
  10. print(type(string_to_int))
  11. # String to Boolean
  12. bool_string = "True"
  13. print(type(bool_string))
  14. string_to_bool = bool(bool_string)
  15. print(type(string_to_bool))

Output

  1. class 'str'
  2. class 'float>
  3. class 'str'
  4. class 'int'
  5. class 'str'
  6. class 'bool'

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

  1. num = 7
  2. print('{0:0>5d}'.format(num)) # left
  3. print('{0:0<5d}'.format(num)) # right
  4. print('{:05d}'.format(num))
  5. print("%0*d" % (5, num))
  6. print(format(num, "05d"))
  7. temp = 'test'
  8. print(temp.rjust(10, '0'))
  9. print(temp.ljust(10, '0'))

Output

  1. 00007
  2. 70000
  3. 00007
  4. 00007
  5. 00007
  6. 000000test
  7. test000000

去掉字符串中的 space 字符

  1. string_var = " \t a string example\n\t\r "
  2. print(string_var)
  3. string_var = string_var.lstrip() # trim white space from left
  4. print(string_var)
  5. string_var = " \t a string example\t "
  6. string_var = string_var.rstrip() # trim white space from right
  7. print(string_var)
  8. string_var = " \t a string example\t "
  9. string_var = string_var.strip() # trim white space from both side
  10. print(string_var)

Output

  1. a string example
  2. a string example
  3. a string example
  4. a string example

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

  1. import string
  2. import random
  3. def string_generator(size):
  4. chars = string.ascii_uppercase + string.ascii_lowercase
  5. return ''.join(random.choice(chars) for _ in range(size))
  6. def string_num_generator(size):
  7. chars = string.ascii_lowercase + string.digits
  8. return ''.join(random.choice(chars) for _ in range(size))
  9. # Random String
  10. test = string_generator(10)
  11. print(test)
  12. # Random String and Number
  13. test = string_num_generator(15)
  14. print(test)

Output

  1. acpPTojXet
  2. qmpah72cjb83eqd

以不同的方式反转字符串

  1. test_string = 'Python Programming'
  2. string_reversed = test_string[-1::-1]
  3. print(string_reversed)
  4. string_reversed = test_string[::-1]
  5. print(string_reversed)
  6. # String reverse logically
  7. def string_reverse(text):
  8. r_text = ''
  9. index = len(text) - 1
  10. while index >= 0:
  11. r_text += text[index]
  12. index -= 1
  13. return r_text
  14. print(string_reverse(test_string))

Output

  1. gnimmargorP nohtyP
  2. gnimmargorP nohtyP
  3. gnimmargorP nohtyP

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

  1. import re
  2. def convert(oldstring):
  3. s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', oldstring)
  4. return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
  5. # Camel Case to Snake Case
  6. print(convert('CamelCase'))
  7. print(convert('CamelCamelCase'))
  8. print(convert('getHTTPResponseCode'))
  9. print(convert('get2HTTPResponseCode'))
  10. # Change Case of a particular character
  11. text = "python programming"
  12. result = text[:1].upper() + text[1:7].lower() \
  13. + text[7:8].upper() + text[8:].lower()
  14. print(result)
  15. text = "Kilometer"
  16. print(text.lower())
  17. old_string = "hello python"
  18. new_string = old_string.capitalize()
  19. print(new_string)
  20. old_string = "Hello Python"
  21. new_string = old_string.swapcase()
  22. print(new_string)

Output

  1. camel_case
  2. camel_camel_case
  3. get_http_response_code
  4. get2_http_response_code
  5. Python Programming
  6. kilometer
  7. Hello python
  8. hELLO pYTHON

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

  1. import re
  2. Continue = 1
  3. Quit = 2
  4. def main():
  5. choice = 0
  6. while choice != Quit:
  7. # Display the menu.
  8. display_menu()
  9. # Constant to assume string is Palindrome
  10. is_palindrome = True
  11. # Get the user's choice.
  12. choice = int(input('\nEnter your choice: '))
  13. # Perform the selected action.
  14. if choice == Continue:
  15. line = input("\nEnter a string: ")
  16. str_lower = re.sub("[^a-z0-9]", "", line.lower())
  17. for i in range(0, len(str_lower)//2):
  18. if str_lower[i] != str_lower[len(str_lower) - i - 1]:
  19. is_palindrome = False
  20. if is_palindrome:
  21. print(line, "is a palindrome")
  22. else:
  23. print(line, "is not a palindrome")
  24. else:
  25. print('Thank You.')
  26. def display_menu():
  27. print('\n*******MENU*******')
  28. print('1) Continue')
  29. print('2) Quit')
  30. main()

Output

  1. *******MENU*******
  2. 1) Continue
  3. 2) Quit
  4. Enter your choice: 1
  5. Enter a string: A dog! A panic in a pagoda!
  6. A dog! A panic in a pagoda! is a palindrome
  7. *******MENU*******
  8. 1) Continue
  9. 2) Quit
  10. Enter your choice: 1
  11. Enter a string: Civic
  12. Civic is a palindrome
  13. *******MENU*******
  14. 1) Continue
  15. 2) Quit
  16. Enter your choice: 1
  17. Enter a string: Python vs Java
  18. Python vs Java is not a palindrome
  19. *******MENU*******
  20. 1) Continue
  21. 2) Quit
  22. Enter your choice: 2
  23. Thank You.

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

  1. str_list = ['aaa', 'bbb', 'ccc', 'ddd'] # list of items
  2. str_test = 'testccc' # string need to test
  3. for str_item in str_list:
  4. if str_test.endswith(str_item):
  5. print("found")
  6. break # loop ends when result found
  7. else:
  8. print("not found")

Output

  1. not found
  2. not found
  3. found

在字符串中应用查找模式

  1. import re
  2. s1 = 'abccba'
  3. s2 = 'abcabc'
  4. s3 = 'canadajapanuaeuaejapancanada'
  5. p = '123321'
  6. def match(s, p):
  7. nr = {}
  8. regex = []
  9. for c in p:
  10. if c not in nr:
  11. regex.append('(.+)')
  12. nr[c] = len(nr) + 1
  13. else:
  14. regex.append('\\%d' % nr[c])
  15. return bool(re.match(''.join(regex) + '$', s))
  16. print(match(s1, p))
  17. print(match(s2, p))
  18. print(match(s3, p))

Output

  1. True
  2. False
  3. True

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

  1. x = 'Canada\\'
  2. print(x.rstrip('\\'))

Output

  1. Canada

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

  1. import re
  2. string = 'canada-japan-india'
  3. print(re.split(r'(\-)', string))

Output

  1. ['canada', '-', 'japan', '-', 'india']

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

  1. string = "asdfHRbySFss"
  2. uppers = [l for l in string if l.isupper()]
  3. print (''.join(uppers))
  4. lowers = [l for l in string if l.islower()]
  5. print (''.join(lowers))

Output

  1. HRSF
  2. asdfbyss

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

  1. myString = 'AAABBB'
  2. for idx, char in enumerate(myString, ):
  3. if idx + 1 == len(myString):
  4. break
  5. if char == myString[idx + 1]:
  6. print(idx, char, myString[idx + 1])

Output

  1. 0 A A
  2. 1 A A
  3. 3 B B
  4. 4 B B

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

  1. string = 'Test5412Test8745Test'
  2. print([string[i:i + 4] for i in range(0, len(string), 4)])

Output

  1. ['Test', '5412', 'Test', '8745', 'Test']

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

  1. str1 = "This is a demo string"
  2. str2 = "This is another demo string"
  3. strz = ("This is a line\n" +
  4. str1 + "\n" +
  5. "This is line 2\n" +
  6. str2 + "\n" +
  7. "This is line 3\n")
  8. print(strz)

Output

  1. This is a line
  2. This is a demo string
  3. This is line 2
  4. This is another demo string
  5. This is line 3

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

  1. volumeA = 100
  2. volumeB = 20
  3. volumeC = 10
  4. vol1 = []
  5. vol2 = []
  6. vol1.extend((volumeA, volumeB, volumeC))
  7. vol2 += [val for name, val in globals().items() if name.startswith('volume')]
  8. print(vol1)
  9. print(vol2)

Output

  1. [100, 20, 10]
  2. [100, 20, 10]

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

  1. s = 'canada'
  2. l = list(s)
  3. print(l)

Output

  1. ['c', 'a', 'n', 'a', 'd', 'a']

如何在 Python 中小写字符串

  1. text = ['Canada', 'JAPAN']
  2. text = [txt.lower() for txt in text]
  3. print(text)

Output

  1. ['canada', 'japan']

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

  1. import re
  2. s = 'a,b,c d!e.f\ncanada\tjapan&germany'
  3. l = re.split('[?.,\n\t&! ]', s)
  4. for i in l:
  5. print(i)

Output

  1. a
  2. b
  3. c
  4. d
  5. e
  6. f
  7. canada
  8. japan
  9. germany

Python 字符串填充

  1. lines_of_text = [
  2. (123, 5487, 'Testing', 'Billy', 'Jones'),
  3. (12345, 100, 'Test', 'John M', 'Smith')
  4. ]
  5. for mytuple in lines_of_text:
  6. name = '{}, {}'.format(mytuple[4], mytuple[3])
  7. value = '$' + str(mytuple[1])
  8. print('{name:<20} {id:>8} {test:<12} {value:>8}'.format(
  9. name=name, id=mytuple[0], test=mytuple[2], value=value)
  10. )

Output

  1. Jones, Billy 123 Testing $5487
  2. Smith, John M 12345 Test $100

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

  1. str1 = 'caars'
  2. str2 = 'rats'
  3. str3 = 'racs'
  4. print(set(str1))
  5. print(set(str2))
  6. print(set(str3))
  7. print(set(str1)==set(str2))
  8. print(set(str1)==set(str3))
  9. print(set(str2)==set(str3))

Output

  1. {'c', 's', 'a', 'r'}
  2. {'t', 's', 'a', 'r'}
  3. {'c', 's', 'a', 'r'}
  4. False
  5. True
  6. False

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

  1. def contains_word(s, w):
  2. return (' ' + w + ' ') in (' ' + s + ' ')
  3. result = contains_word('those who seek shall find', 'find')
  4. print(result)
  5. result = contains_word('those who seek shall find', 'finds')
  6. print(result)

Output

  1. True
  2. False

查找所有出现的子字符串

  1. import re
  2. aString = 'this is a string where the substring "is" is repeated several times'
  3. print([(a.start(), a.end()) for a in list(re.finditer('is', aString))])

Output

  1. [(2, 4), (5, 7), (38, 40), (42, 44)]

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

  1. from string import punctuation
  2. s = '.$958-5-Canada,#'
  3. print(s.strip(punctuation))

Output

  1. 958-5-Canada

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

  1. s = 'canada/japan/australia'
  2. l = s.split('/')
  3. print(l)

Output

  1. ['canada', 'japan', 'australia']

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

  1. def capitalize(s, ind):
  2. split_s = list(s)
  3. for i in ind:
  4. try:
  5. split_s[i] = split_s[i].upper()
  6. except IndexError:
  7. print('Index out of range : ', i)
  8. return "".join(split_s)
  9. print(capitalize("abracadabra", [2, 6, 9, 10, 50])

Output

  1. Index out of range : 50
  2. abRacaDabRA

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

  1. a = "1000"
  2. x = a.isdigit()
  3. print(x)
  4. b = "A1000"
  5. x = b.isdigit()
  6. print(x)

Output

  1. True
  2. False

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

  • is用于同一性比较
  • ==用于相等性比较 ```python a = ‘canada’ b = ‘’.join([‘ca’, ‘na’, ‘da’]) print(a == b) print(a is b)

a = [1, 2, 3] b = [1, 2, 3] print(a == b) print(a is b)

c = b print(c is b)

  1. <a name="dzltw"></a>
  2. ### Output
  3. ```python
  4. True
  5. False
  6. True
  7. False
  8. True

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

  1. print('canada'.ljust(10) + 'india'.ljust(20) + 'japan')

Output

  1. canada india japan

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

  1. def nth_replace(str,search,repl,index):
  2. split = str.split(search,index+1)
  3. if len(split)<=index+1:
  4. return str
  5. return search.join(split[:-1])+repl+split[-1]
  6. str1 = "caars caars caars"
  7. str2 = nth_replace(str1, 'aa', 'a', 1)
  8. print(str2)

Output

  1. caars cars caars

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

  1. int1 = 10
  2. str1 = 'test'
  3. print(str(int1) + str1)

Output

  1. 10test

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

  1. s = r'canada\japan\australia'
  2. l = s.split('\\')
  3. print(l)

Output

  1. ['canada', 'japan', 'australia']

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

  1. from random import choice
  2. x = "canada japan australia"
  3. print(''.join(choice((str.upper, str.lower))(c) for c in x))

Output

  1. CANaDA JaPan auStRALIa

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

  1. import re
  2. string = "Canada AND Japan NOT Audi OR BMW"
  3. l = re.split(r'(AND|OR|NOT)', string)
  4. print(l)

Output

  1. ['Canada ', 'AND', ' Japan ', 'NOT', ' Audi ', 'OR', ' BMW']

在 Python 中填充 n 个字符

  1. def header(txt: str, width=30, filler='*', align='c'):
  2. assert align in 'lcr'
  3. return {'l': txt.ljust, 'c': txt.center, 'r': txt.rjust}[align](width, filler)
  4. print(header("Canada"))
  5. print(header("Canada", align='l'))
  6. print(header("Canada", align='r'))

Output

  1. ************Canada************
  2. Canada************************
  3. ************************Canada

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

  1. x = 'canada'
  2. if x in ['canada', 'japan', 'germany', 'australia']:
  3. print("Yes")

Output

  1. true

Python字符串格式化固定宽度

  1. num1 = 0.04154721841
  2. num2 = 10.04154721841
  3. num3 = 1002.04154721841
  4. print "{0:<12.11g}".format(num1)[:12]
  5. print "{0:<12.11g}".format(num2)[:12]
  6. print "{0:<12.11g}".format(num3)[:12]

Output

  1. 100.041549
  2. 0.04159874
  3. 12.8878877

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

  1. test = 'canada#japan#uae'
  2. c = '#'
  3. print([pos for pos, char in enumerate(test) if char == c])

Output

  1. [6, 12]

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

  1. def trim(text, num_of_leading, num_of_trailing):
  2. text = list(text)
  3. for i in range(num_of_leading):
  4. if text[i] == " ":
  5. text[i] = ""
  6. else:
  7. break
  8. for i in range(1, num_of_trailing+1):
  9. if text[-i] == " ":
  10. text[-i] = ""
  11. else:
  12. break
  13. return ''.join(text)
  14. txt1 = " Candada "
  15. print(trim(txt1, 1, 1))
  16. print(trim(txt1, 2, 3))
  17. print(trim(txt1, 6, 8))

Output

  1. Candada
  2. Candada
  3. Candada

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

  1. str = 'canadajapan'
  2. splitat = 6
  3. l, r = str[:splitat], str[splitat:]
  4. print(l)
  5. print(r)

Output

  1. canada
  2. japan

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

  1. string = "canada"
  2. result = string[0:1].upper() + string[1:-1].lower() + string[-1:].upper()
  3. print(result)

Output

  1. CanadA

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

  1. txt = "Canada is a great country"
  2. x = txt.endswith("country")
  3. print(x)

Output

  1. True

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

  1. str1 = "Canada"
  2. str2 = "Canada"
  3. print(str1 is str2) # True
  4. print(str1 == str2) # True
  5. string1 = ''.join(['Ca', 'na', 'da'])
  6. string2 = ''.join(['Can', 'ada'])
  7. print(string1 is string2) # False
  8. print(string1 == string2) # True

Output

  1. True
  2. True
  3. False
  4. True

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

  1. x = 4
  2. x = str(x).zfill(5)
  3. print(x)

Output

  1. 00004

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

  1. s = "The quick brown fox jumps over the lazy dog"
  2. for r in (("brown", "red"), ("lazy", "quick")):
  3. s = s.replace(*r)
  4. print(s)

Output

  1. The quick red fox jumps over the quick dog

Python字符串替换字符

  1. s = "The quick brown fox jumps over the lazy dog"
  2. for r in (("brown", "red"), ("lazy", "quick")):
  3. s = s.replace(*r)
  4. print(s)

Output

  1. The quick red fox jumps over the quick dog

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

  1. import re
  2. sentence = 'this is a sentence this this'
  3. word = 'this'
  4. for match in re.finditer(word, sentence):
  5. print(match.start(), match.end())

Output

  1. 0 4
  2. 19 23
  3. 24 28

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

  1. import string
  2. x = "they're bill's friends from the UK"
  3. x = string.capwords(x)
  4. print(x)
  5. x = x.title()
  6. print(x)

Output

  1. They're Bill's Friends From The Uk
  2. They'Re Bill'S Friends From The Uk

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

  1. s = '"Canada", "Japan", "Germany", "Russia"'
  2. l = ['"{}"'.format(s) for s in s.split('"') if s not in ('', ', ')]
  3. for item in l:
  4. print(item)

Output

  1. "Canada"
  2. "Japan"
  3. "Germany"
  4. "Russia"

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

  1. string1 = "Canada"
  2. print(len(string1.encode('utf-16')))

Output

  1. 10

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

  1. myString = 'AAABBB'
  2. for idx, char in enumerate(myString, ):
  3. if idx + 1 == len(myString):
  4. break
  5. if char == myString[idx + 1]:
  6. print(idx, char, myString[idx + 1])int1 = 10
  7. str1 = 'test'
  8. print(str(int1) + str1)

Output

  1. 0 A A
  2. 1 A A
  3. 3 B B
  4. 4 B B

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

  1. import re
  2. test = "example(test)"
  3. test2 = "example(test)example"
  4. test3 = "(test)example"
  5. test4 = "example (test) example"
  6. for i in [test, test2, test3, test4]:
  7. print(re.sub(r"[^\S]?(\(.*?\))[^\S]?", r" \1 ", i).strip())

Output

  1. example (test)
  2. example (test) example
  3. (test) example
  4. example (test) example

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

  1. s = ' canada '
  2. print(s.strip())

Output

  1. canada

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

  1. s = 'canada-japan-australia'
  2. l = s.split('-')[0]
  3. print(l)
  4. string = 'canada-japan-australia'
  5. print(string[:string.index('-')])

Output

  1. canada
  2. canada

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

  1. words = ['The', 'quick', 'BROWN', 'Fox',
  2. 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
  3. print([word for word in words if word.islower()])
  4. print([word for word in words if word.isupper()])
  5. print([word for word in words if not word.islower() and not word.isupper()])

Output

  1. ['quick', 'jumped', 'the']
  2. ['BROWN', 'OVER', 'DOG']
  3. ['The', 'Fox', 'Lazy']

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

  1. txt = "I love Canada, Canada is one of the most impressive countries in the world. Canada is a great country."
  2. x = txt.count("Canada")
  3. print(x)

Output

  1. 3

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

  1. hour = 4
  2. minute = 3
  3. print("{:0>2}:{:0>2}".format(hour, minute))
  4. print("{:0>3}:{:0>5}".format(hour, minute))
  5. print("{:0<3}:{:0<5}".format(hour, minute))
  6. print("{:$<3}:{:#<5}".format(hour, minute))

Output

  1. 04:03
  2. 004:00003
  3. 400:30000
  4. 4$$:3####

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

  1. from string import ascii_letters, digits
  2. def compare_alphanumeric(first, second):
  3. for character in first:
  4. if character in ascii_letters + digits and character not in second:
  5. return False
  6. return True
  7. str1 = 'ABCD'
  8. str2 = 'ACDB'
  9. print(compare_alphanumeric(str1, str2))
  10. str1 = 'A45BCD'
  11. str2 = 'ACD59894B'
  12. print(compare_alphanumeric(str1, str2))
  13. str1 = 'A45BCD'
  14. str2 = 'XYZ9887'
  15. print(compare_alphanumeric(str1, str2))

Output

  1. True
  2. True
  3. False

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

  1. s = "CANADA"
  2. print(" ".join(s))
  3. print("-".join(s))
  4. print(s.replace("", " ")[1: -1])

Output

  1. C A N A D A
  2. C-A-N-A-D-A
  3. C A N A D A

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

  1. s = 'What is Canada famous for?'
  2. print(s.find('f'))
  3. print(s.index('f'))
  4. print(s.rindex('f'))
  5. print(s.rfind('f'))

Output

  1. 15
  2. 15
  3. 22
  4. 22

在 Python 中将字符串首字母大写

  1. x = 'canada'
  2. x = x.capitalize()
  3. print(x)

Output

  1. Canada

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

  1. import re
  2. s = "65&Can-Jap#Ind^UK"
  3. l = re.split('([^a-zA-Z0-9])', s)
  4. print(l)

Output

  1. ['65', '&', 'Can', '-', 'Jap', '#', 'Ind', '^', 'UK']

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

  1. string = "asdfHRbySFss"
  2. uppers = [l for l in string if l.isupper()]
  3. print(len(uppers))
  4. lowers = [l for l in string if l.islower()]
  5. print(len(lowers))

Output

  1. 4
  2. 8

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

  1. from enum import Enum, auto
  2. class Signal(Enum):
  3. red = auto()
  4. green = auto()
  5. orange = auto()
  6. def equals(self, string):
  7. return self.name == string
  8. brain_detected_colour = "red"
  9. print(Signal.red.equals(brain_detected_colour))
  10. brain_detected_colour = "pink"
  11. print(Signal.red.equals(brain_detected_colour))

Output

  1. True
  2. False

Python中的段落格式

  1. import textwrap
  2. hamlet = '''\
  3. Lorum ipsum is the traditional Latin placeholder text, used when a designer needs a chunk of text for dummying up a layout.
  4. Journo Ipsum is like that, only using some of the most common catchphrases, buzzwords, and bon mots of the future-of-news crowd.
  5. Hit reload for a new batch. For entertainment purposes only.'''
  6. wrapper = textwrap.TextWrapper(initial_indent='\t' * 1,
  7. subsequent_indent='\t' * 2,
  8. width=40)
  9. for para in hamlet.splitlines():
  10. print(wrapper.fill(para))

Output

  1. Lorum ipsum is the traditional Latin
  2. placeholder text, used when a designer
  3. needs a chunk of text for dummying up
  4. a layout.
  5. Journo Ipsum is like that, only using
  6. some of the most common catchphrases,
  7. buzzwords, and bon mots of the future-
  8. of-news crowd.
  9. Hit reload for a new batch. For
  10. entertainment purposes only.

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

  1. def nth_replace(str,search,repl,index):
  2. split = str.split(search,index+1)
  3. if len(split)<=index+1:
  4. return str
  5. return search.join(split[:-1])+repl+split[-1]
  6. str1 = "caars caars caars"
  7. str2 = nth_replace(str1, 'aa', 'a', 1)
  8. print(str2)

Output

  1. caars cars caars

如何连接 str 和 int 对象

  1. i = 123
  2. a = "foobar"
  3. s = a + str(i)
  4. print(s)

Output

  1. foobar123

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

  1. s = 'canada japan australia'
  2. l = s.split(' ', 1)
  3. print(l)

Output

  1. ['canada', 'japan australia']

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

  1. text = ['CANADA', 'JAPAN']
  2. text = [txt.capitalize() for txt in text]
  3. print(text)

Output

  1. ['Canada', 'Japan']

在标点符号上拆分字符串

  1. string = 'a,b,c d!e.f\ncanada\tjapan&germany'
  2. identifiers = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\n\t '
  3. listitems = "".join((' ' if c in identifiers else c for c in string)).split()
  4. for item in listitems:
  5. print(item)

Output

  1. a
  2. b
  3. c
  4. d
  5. e
  6. f
  7. canada
  8. japan
  9. germany

在 Python 中比较字符串

  1. str1 = "Canada"
  2. str2 = "Canada"
  3. print(str1 is str2) # True
  4. print(str1 == str2) # True
  5. string1 = ''.join(['Ca', 'na', 'da'])
  6. string2 = ''.join(['Can', 'ada'])
  7. print(string1 is string2) # False
  8. print(string1 == string2) # True

Output

  1. True
  2. True
  3. False
  4. True

用零填充数字字符串

  1. num = 123
  2. print('{:<08d}'.format(num))
  3. print('{:>08d}'.format(num))
  4. string = '123'
  5. print(string.ljust(8, '0'))
  6. print(string.rjust(8, '0'))
  7. print(string[::-1].zfill(8)[::-1])

Output

  1. 12300000
  2. 00000123
  3. 12300000
  4. 00000123
  5. 12300000

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

  1. def dif(a, b):
  2. return [i for i in range(len(a)) if a[i] != b[i]]
  3. print(dif('stackoverflow', 'stacklavaflow'))

Output

  1. [5, 6, 7, 8]

Python填充字符串到固定长度

  1. number = 4
  2. print(f'{number:05d}') # (since Python 3.6), or
  3. print('{:05d}'.format(number)) # or
  4. print('{0:05d}'.format(number))
  5. print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
  6. print(format(number, '05d'))

Output

  1. 00004
  2. 00004
  3. 00004
  4. 00004
  5. 00004
  6. 00004

Python中的字符串查找示例

  1. import re
  2. text = 'This is sample text to test if this pythonic '\
  3. 'program can serve as an indexing platform for '\
  4. 'finding words in a paragraph. It can give '\
  5. 'values as to where the word is located with the '\
  6. 'different examples as stated'
  7. find_the_word = re.finditer('as', text)
  8. for match in find_the_word:
  9. print('start {}, end {}, search string \'{}\''.
  10. format(match.start(), match.end(), match.group()))

Output

  1. start 63, end 65, search string 'as'
  2. start 140, end 142, search string 'as'
  3. start 200, end 202, search string 'as'

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

  1. list_num = ['000231512-n', '1209123100000-n00000',
  2. 'alphanumeric0000', '000alphanumeric']
  3. print([item.strip('0') for item in list_num]) # Remove leading + trailing '0'
  4. print([item.lstrip('0') for item in list_num]) # Remove leading '0'
  5. print([item.rstrip('0') for item in list_num]) # Remove trailing '0'

Output

  1. ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
  2. ['231512-n', '1209123100000-n00000', 'alphanumeric0000', 'alphanumeric']
  3. ['000231512-n', '1209123100000-n', 'alphanumeric', '000alphanumeric']

Python在换行符上拆分

  1. s = 'line 1\nline 2\nline without newline'
  2. l = s.splitlines(True)
  3. print(l)

Output

  1. ['line 1\n', 'line 2\n', 'line without newline']

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

  1. s = 'canada'
  2. s = "".join([x.upper() if i % 2 != 0 else x for i, x in enumerate(s)])
  3. print(s)

Output

  1. cAnAdA

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

  1. import calendar
  2. def last_business_day_in_month(year: int, month: int) -> int:
  3. return max(calendar.monthcalendar(year, month)[-1:][0][:5])
  4. print(last_business_day_in_month(2021, 1))
  5. print(last_business_day_in_month(2021, 2))
  6. print(last_business_day_in_month(2021, 3))
  7. print(last_business_day_in_month(2021, 4))
  8. print(last_business_day_in_month(2021, 5))

Output

  1. 29
  2. 26
  3. 31
  4. 30
  5. 31

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

  1. def compare_strings(a, b):
  2. result = True
  3. if len(a) != len(b):
  4. print('string lengths do not match!')
  5. for i, (x, y) in enumerate(zip(a, b)):
  6. if x != y:
  7. print(f'char miss-match {x, y} in element {i}')
  8. result = False
  9. if result:
  10. print('strings match!')
  11. return result
  12. print(compare_strings("canada", "japan"))

Output

  1. string lengths do not match!
  2. char miss-match ('c', 'j') in element 0
  3. char miss-match ('n', 'p') in element 2
  4. char miss-match ('d', 'n') in element 4
  5. False

在 Python 中多次显示字符串

  1. print('canada' * 3)
  2. print(*3 * ('canada',), sep='-')

Output

  1. canadacanadacanada
  2. canada-canada-canada

Python从头开始替换字符串

  1. def nth_replace(s, old, new, occurrence):
  2. li = s.rsplit(old, occurrence)
  3. return new.join(li)
  4. str1 = "caars caars caars caars caars"
  5. str2 = nth_replace(str1, 'aa', 'a', 1)
  6. print(str2)
  7. str2 = nth_replace(str1, 'aa', 'a', 2)
  8. print(str2)
  9. str2 = nth_replace(str1, 'aa', 'a', 3)
  10. print(str2)

Output

  1. caars caars caars caars cars
  2. caars caars caars cars cars
  3. caars caars cars cars cars

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

  1. year = '2020'
  2. print('test' + str(year))
  3. print('test' + year.__str__())

Output

  1. test2020
  2. test2020

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

  1. s = 'canada_japan_australia_us_uk'
  2. l = s.split('_', 0)
  3. print(l)
  4. l = s.split('_', 1)
  5. print(l)
  6. l = s.split('_', 2)
  7. print(l)

Output

  1. ['canada_japan_australia_us_uk']
  2. ['canada', 'japan_australia_us_uk']
  3. ['canada', 'japan', 'australia_us_uk']

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

  1. text = ['johnny rotten', 'eddie vedder', 'kurt kobain',
  2. 'chris cornell', 'micheal phillip jagger']
  3. text = [txt.capitalize() for txt in text]
  4. print(text)

Output

  1. ['Johnny rotten', 'Eddie vedder', 'Kurt kobain', 'Chris cornell', 'Micheal phillip jagger']

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

  1. test = 'Position of a character'
  2. print(test.find('of'))
  3. print(test.find('a'))

Output

  1. 9
  2. 12

不同长度的Python填充字符串

  1. data = [1148, 39, 365, 6, 56524]
  2. for element in data:
  3. print("{:>5}".format(element))

Output

  1. 1148
  2. 39
  3. 365
  4. 6
  5. 56524

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

  1. def after(s1, s2):
  2. index = s1.find(s2)
  3. if index != -1 and index + len(s2) < len(s1):
  4. return s1[index + len(s2):]
  5. else:
  6. return None
  7. s1 = "canada"
  8. s2 = "can"
  9. print(after(s1, s2))

Output

  1. ada

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

  1. test = 'canada'
  2. print('$' * len(test))

Output

  1. $$$$$$

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

  1. def find_str(s, char):
  2. index = 0
  3. if char in s:
  4. c = char[0]
  5. for ch in s:
  6. if ch == c:
  7. if s[index:index + len(char)] == char:
  8. return index
  9. index += 1
  10. return -1
  11. print(find_str("India Canada Japan", "Canada"))
  12. print(find_str("India Canada Japan", "cana"))
  13. print(find_str("India Canada Japan", "Uae"))

Output

  1. 6
  2. -1
  3. -1

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

  1. number = '+91 874854778'
  2. print(number.strip('+'))
  3. print(number.lstrip('+91'))

Output

  1. 91 874854778
  2. 874854778

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

  1. string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2. x = 3
  3. res = [string[y - x:y] for y in range(x, len(string) + x, x)]
  4. print(res)

Output

  1. ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ']

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

  1. s = "xxxyyyzzz"
  2. # convert to list
  3. a = list(s)
  4. # change every third letter in place with a list comprehension
  5. a[2::3] = [x.upper() for x in a[2::3]]
  6. # back to a string
  7. s = ''.join(a)
  8. print(s)

Output

  1. xxXyyYzzZ

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

  1. txt = "Canada\tis\ta\tgreat\tcountry"
  2. print(txt)
  3. print(txt.expandtabs())
  4. print(txt.expandtabs(2))
  5. print(txt.expandtabs(4))
  6. print(txt.expandtabs(10))

Output

  1. Canada is a great country
  2. Canada is a great country
  3. Canada is a great country
  4. Canada is a great country
  5. Canada is a great country

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

  1. str1 = "Can"
  2. str2 = "Canada"
  3. print(str1 in str2)
  4. print(str1.startswith(str2))
  5. print(str2.startswith(str1))
  6. print(str1.endswith(str2))
  7. str3 = "CAN"
  8. print(str3 in str2)

Output

  1. True
  2. False
  3. True
  4. False
  5. False

字符串格式化填充负数

  1. n = [-2, -8, 1, -10, 40]
  2. num = ["{1:0{0}d}".format(2 if x >= 0 else 3, x) for x in n]
  3. print(num)

Output

  1. n = [-2, -8, 1, -10, 40]
  2. num = ["{1:0{0}d}".format(2 if x >= 0 else 3, x) for x in n]
  3. print(num)

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

  1. str1 = "caars caars caars"
  2. str2 = str1.replace('aa', 'a', 1)
  3. print(str2)

Output

  1. cars caars caars

连接固定字符串和变量

  1. variable = 'Hello'
  2. print('This is the Test File ' + variable)
  3. variable = '10'
  4. print('This is the Test File ' + str(variable))

Output

  1. This is the Test File Hello
  2. This is the Test File 10

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

  1. s = 'str1, str2, str3, str4'
  2. l = s.split(', ')
  3. print(l)

Output

  1. ['str1', 'str2', 'str3', 'str4']

在 Python 中将字符串大写

  1. x = "canada japan australia"
  2. x = x[:1].upper() + x[1:]
  3. print(x)
  4. x= x.capitalize()
  5. print(x)
  6. x= x.title()
  7. print(x)

Output

  1. Canada japan australia
  2. Canada japan australia
  3. Canada Japan Australia

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

  1. data = b'\x00\x00\x00\x00\x00\x00'
  2. info = [data[i:i + 2] for i in range(0, len(data), 2)]
  3. print(info)

Output

  1. [b'\x00\x00', b'\x00\x00', b'\x00\x00']

用空格填写 Python 字符串

  1. string = 'Hi'.ljust(10)
  2. print(string)
  3. string = 'Hi'.rjust(10)
  4. print(string)
  5. string = '{0: ^20}'.format('Hi')
  6. print(string)
  7. string = '{message: >16}'.format(message='Hi')
  8. print(string)
  9. string = '{message: <16}'.format(message='Hi')
  10. print(string)
  11. string = '{message: <{width}}'.format(message='Hi', width=20)
  12. print(string)

Output

  1. Hi
  2. Hi
  3. Hi
  4. Hi
  5. Hi
  6. Hi

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

  1. from collections import Counter
  2. def shared_chars(s1, s2):
  3. return sum((Counter(s1) & Counter(s2)).values())
  4. print(shared_chars('car', 'carts'))

Output

  1. 3

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

  1. import re
  2. s = "ABC24.00XYZ58.28PQR"
  3. s = re.sub("[A-Za-z]+", lambda group: " " + group[0] + " ", s)
  4. print(s.strip())

Output

  1. ABC 24.00 XYZ 58.28 PQR

如何在 Python 中去除空格

  1. s = ' canada '
  2. print(s.rstrip()) # For whitespace on the right side use rstrip.
  3. print(s.lstrip()) # For whitespace on the left side lstrip.
  4. print(s.strip()) # For whitespace from both side.
  5. s = ' \t canada '
  6. print(s.strip('\t')) # This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

Output

  1. canada
  2. canada
  3. canada
  4. canada

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

  1. s = 'canada-japan-australia-uae-india'
  2. l = s.rsplit('-', 1)[1]
  3. print(l)

Output

  1. india

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

  1. string = "canada"
  2. result = string[:-1] + string[-1].upper()
  3. print(result)
  4. result = string[::-1].title()[::-1]
  5. print(result)

Output

  1. canadA
  2. canadA

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

  1. txt = "canada"
  2. x = txt.center(20)
  3. print(x)

Output

  1. canada

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

  1. x = 4
  2. w = 5
  3. print('{number:0{width}d}'.format(width=w, number=x))

Output

  1. 00004

在 Python 中使用 string.replace()

  1. a = "This is the island of istanbul"
  2. print (a.replace("is" , "was", 1))
  3. print (a.replace("is" , "was", 2))
  4. print (a.replace("is" , "was"))

Output

  1. Thwas is the island of istanbul
  2. Thwas was the island of istanbul
  3. Thwas was the wasland of wastanbul

在 Python 中获取字符的位置

  1. test = 'Position of a character'
  2. print(test.find('of'))
  3. print(test.find('a'))

Output

  1. 9
  2. 12

Python字符串替换多次出现

  1. s = "The quick brown fox jumps over the lazy dog"
  2. for r in (("brown", "red"), ("lazy", "quick")):
  3. s = s.replace(*r)
  4. print(s)

Output

  1. The quick red fox jumps over the quick dog

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

  1. string = 'This + is + a + string'
  2. x = string.find('+', 4)
  3. print(x)
  4. x = string.find('+', 10)
  5. print(x)

Output

  1. 5
  2. 10

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

  1. x = 'canada'
  2. x = x.upper()
  3. print(x)

Output

  1. CANADA

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

  1. import re
  2. l = re.split(r'[$-]+', 'canada$-india$-japan$-uae')
  3. print(l)

Output

  1. ['canada', 'india', 'japan', 'uae']

在 Python 中获取字符串的大小

  1. string1 = "Canada"
  2. print(len(string1))
  3. string2 = " Canada"
  4. print(len(string2))
  5. string3 = "Canada "
  6. print(len(string3))

Output

  1. 6
  2. 8
  3. 8

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

  1. import re
  2. text = ['123', 'abc', '4x5x6', '7.2volt', '60BTU',
  3. '20v', '4*5', '24in', 'google.com-1.2', '1.2.3']
  4. pattern = r'(-?[0-9]+\.?[0-9]*)'
  5. for data in text:
  6. print(repr(data), repr(
  7. ' '.join(segment for segment in re.split(pattern, data) if segment)))

Output

  1. '123' '123'
  2. 'abc' 'abc'
  3. '4x5x6' '4 x 5 x 6'
  4. '7.2volt' '7.2 volt'
  5. '60BTU' '60 BTU'
  6. '20v' '20 v'
  7. '4*5' '4 * 5'
  8. '24in' '24 in'
  9. 'google.com-1.2' 'google.com -1.2'
  10. '1.2.3' '1.2 . 3'

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

  1. s = 'canada japan australia'
  2. l = s.split(' ', 1)
  3. print(l)

Output

  1. ['canada', 'japan australia']

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

  1. indices = set([0, 7, 14, 18])
  2. s = "i love canada and japan"
  3. print("".join(c.upper() if i in indices else c for i, c in enumerate(s)))

Output

  1. I love Canada And Japan

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

  1. import re
  2. thestring = "a,b,c d!e.f\ncanada\tjapan&germany"
  3. listitems = re.findall('\w+', thestring)
  4. for item in listitems:
  5. print(item)

Output

  1. a
  2. b
  3. c
  4. d
  5. e
  6. f
  7. canada
  8. japan
  9. germany

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

  1. str1 = 'caars'
  2. str2 = 'rats'
  3. str3 = 'racs'
  4. print(set(str1)==set(str2))
  5. print(set(str1)==set(str3))

Output

  1. False
  2. True

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

  1. import re
  2. string_test = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  3. print(re.findall(r"[\w']+", string_test))
  4. def split_by_char(s, seps):
  5. res = [s]
  6. for sep in seps:
  7. s, res = res, []
  8. for seq in s:
  9. res += seq.split(sep)
  10. return res
  11. print(split_by_char(string_test, [' ', '(', ')', ',']))

Output

  1. ['Ethnic', '279', 'Responses', '3', '2016', 'Census', '25', 'Sample']
  2. ['Ethnic', '', '279', '', '', 'Responses', '', '3', '', '', '2016', 'Census', '-', '25%', 'Sample']

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

  1. # Example 1
  2. str1 = "Can"
  3. str2 = "ada"
  4. str3 = str1 + str2
  5. print(str3)
  6. # Example 2
  7. str4 = 'Ca'
  8. str4 += 'na'
  9. str4 += 'da'
  10. print(str4)
  11. # Example 3
  12. join_str = "".join((str1, str2))
  13. print(join_str)
  14. # Example 4
  15. str_add = str1.__add__(str2)
  16. print(str_add)

Output

  1. Canada
  2. Canada
  3. Canada
  4. Canada

在 Python 中遍历字符串

  1. # Example 1
  2. test_str = "Canada"
  3. for i, c in enumerate(test_str):
  4. print(i, c)
  5. print("------------------------")
  6. # Example 2
  7. indx = 0
  8. while indx < len(test_str):
  9. print(indx, test_str[indx])
  10. indx += 1
  11. print("------------------------")
  12. # Example 3
  13. for char in test_str:
  14. print(char)

Output

  1. 0 C
  2. 1 a
  3. 2 n
  4. .......
  5. d
  6. a

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

  1. import string
  2. import re
  3. # Example 1
  4. s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  5. out = re.sub(r'[^\w\s]', '', s)
  6. print(out)
  7. # Example 2
  8. s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  9. for p in string.punctuation:
  10. s = s.replace(p, "")
  11. print(s)
  12. # Example 3
  13. s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  14. out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
  15. print(out)

Output

  1. Ethnic 279 Responses 3 2016 Census 25 Sample
  2. Ethnic 279 Responses 3 2016 Census 25 Sample
  3. Ethnic 279 Responses 3 2016 Census 25 Sample

将列表转换为字符串

  1. list_exp = ['Ca', 'na', 'da']
  2. print(type(list_exp))
  3. # Example 1
  4. str_exp1 = ''.join(list_exp)
  5. print(type(str_exp1))
  6. print(str_exp1)
  7. # Example 2
  8. str_exp2 = ''.join(str(e) for e in list_exp)
  9. print(type(str_exp2))
  10. print(str_exp2)
  11. # Example 3
  12. str_exp3 = ''.join(map(str, list_exp))
  13. print(type(str_exp2))
  14. print(str_exp2)

Output

  1. class 'list'
  2. class 'str'
  3. Canada
  4. class 'str'
  5. Canada
  6. class 'str'
  7. Canada

将 JSON 转换为字符串

  1. import json
  2. # list with dict a simple Json format
  3. json_exp = \
  4. [{"id": "12", "name": "Mark"}, {"id": "13", "name": "Rock", "date": None}]
  5. print(type(json_exp))
  6. str_conv = json.dumps(json_exp) # string
  7. print(type(str_conv))
  8. print(str_conv)

Output

  1. class 'list'
  2. class 'str'
  3. [{"id": "12", "name": "Mark"}, {"id": "13", "name": "Rock", "date": null}]

对字符串列表进行排序

  1. # Example 1
  2. str_list = ["Japan", "Canada", "Australia"]
  3. print(str_list)
  4. str_list.sort()
  5. print(str_list)
  6. # Example 2
  7. str_list = ["Japan", "Canada", "Australia"]
  8. for x in sorted(str_list):
  9. print(x)
  10. # Example 3
  11. str_var = "Canada"
  12. strlist = sorted(str_var)
  13. print(strlist)

Output

  1. ['Japan', 'Canada', 'Australia']
  2. ['Australia', 'Canada', 'Japan']
  3. Australia
  4. Canada
  5. Japan
  6. ['C', 'a', 'a', 'a', 'd', 'n']

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

  1. import re
  2. exp_str = "Python Programming"
  3. # Example 1
  4. if re.match(r'^Python', exp_str):
  5. print(True)
  6. else:
  7. print(False)
  8. # Example 2
  9. result = exp_str.startswith("Python")
  10. print(result)

Output

  1. True
  2. True

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

  1. str1 = "AAAA"
  2. str2 = "BBBBBBBBB"
  3. # Example 1
  4. mesh = "".join(i + j for i, j in zip(str1, str2))
  5. print("Example 1:", mesh)
  6. # Example 2
  7. min_len = min(len(str1), len(str2))
  8. mesh = [''] * min_len * 2
  9. mesh[::2] = str1[:min_len]
  10. mesh[1::2] = str2[:min_len]
  11. print("Example 2:", ''.join(mesh))
  12. # Example 3
  13. mesh = ''.join(''.join(item) for item in zip(str1, str2))
  14. print("Example 3:", mesh)
  15. # Example 4
  16. min_len = min(len(str1), len(str2))
  17. mesh = [''] * min_len * 2
  18. mesh[::2] = str1[:min_len]
  19. mesh[1::2] = str2[:min_len]
  20. mesh += str1[min_len:] + str2[min_len:]
  21. print("Example 4:", ''.join(mesh))

Output

  1. Example 1: ABABABAB
  2. Example 2: ABABABAB
  3. Example 3: ABABABAB
  4. Example 4: ABABABABBBBBB