日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python之字符串的134个常用操作

發布時間:2024/5/28 python 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python之字符串的134个常用操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、字符串切片操作

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)
  • 執行結果:
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 Countersentence = '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'])
  • 執行結果:
Empty Empty Empty

三、計算字符串中字符出現次數的多種方法

import re from collections import Countersentence = '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'])
  • 執行結果:
6 6 6

四、將 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))
  • 執行結果:
class 'str' class 'float> class 'str' class 'int' class 'str' class 'bool'

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

num = 7print('{0:0>5d}'.format(num)) # left print('{0:0<5d}'.format(num)) # rightprint('{:05d}'.format(num))print("%0*d" % (5, num)) print(format(num, "05d"))temp = 'test' print(temp.rjust(10, '0')) print(temp.ljust(10, '0'))
  • 執行結果:
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)string_var = " \t a string example\t " string_var = string_var.strip() # trim white space from both side print(string_var)
  • 執行結果:
a string example a string examplea string example a string example

七、生成 N 個字符的隨機字符串

import string import randomdef string_generator(size):chars = string.ascii_uppercase + string.ascii_lowercasereturn ''.join(random.choice(chars) for _ in range(size))def string_num_generator(size):chars = string.ascii_lowercase + string.digitsreturn ''.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)
  • 執行結果:
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) - 1while index >= 0:r_text += text[index]index -= 1return r_textprint(string_reverse(test_string))
  • 執行結果:
gnimmargorP nohtyPgnimmargorP nohtyPgnimmargorP nohtyP

九、將 Camel Case 轉換為 Snake Case 并更改給定字符串中特定字符的大小寫

import redef 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)
  • 執行結果:
camel_case camel_camel_case get_http_response_code get2_http_response_code Python Programming kilometer Hello python hELLO pYTHON

十、檢查給定的字符串是否是 Python 中的回文字符串

import reContinue = 1 Quit = 2def main():choice = 0while choice != Quit:# Display the menu.display_menu()# Constant to assume string is Palindromeis_palindrome = True# Get the user's choice.choice = int(input('\nEnter your choice: '))# Perform the selected action.if choice == Continue:line = input("\nEnter a string: ")str_lower = re.sub("[^a-z0-9]", "", line.lower())for i in range(0, len(str_lower)//2):if str_lower[i] != str_lower[len(str_lower) - i - 1]:is_palindrome = Falseif is_palindrome:print(line, "is a palindrome")else:print(line, "is not a palindrome")else:print('Thank You.') def display_menu():print('\n*******MENU*******')print('1) Continue')print('2) Quit') main()
  • 執行結果:
*******MENU******* 1) Continue 2) Quit Enter your choice: 1 Enter a string: A dog! A panic in a pagoda! A dog! A panic in a pagoda! is a palindrome*******MENU******* 1) Continue 2) Quit Enter your choice: 1 Enter a string: Civic Civic is a palindrome*******MENU******* 1) Continue 2) Quit Enter your choice: 1 Enter a string: Python vs Java Python vs Java is not a palindrome*******MENU******* 1) Continue 2) Quit Enter your choice: 2 Thank You.

十一、檢查字符串是否以列表中的一個字符串結尾

str_list = ['aaa', 'bbb', 'ccc', 'ddd'] # list of items str_test = 'testccc' # string need to testfor str_item in str_list:if str_test.endswith(str_item):print("found")break # loop ends when result foundelse:print("not found")
  • 執行結果:
not found not found found

十二、在字符串中應用查找模式

import res1 = 'abccba' s2 = 'abcabc' s3 = 'canadajapanuaeuaejapancanada' p = '123321'def match(s, p):nr = {}regex = []for c in p:if c not in nr:regex.append('(.+)')nr[c] = len(nr) + 1else:regex.append('\\%d' % nr[c])return bool(re.match(''.join(regex) + '$', s))print(match(s1, p)) print(match(s2, p)) print(match(s3, p))
  • 執行結果:
True False True

十三、如果是 Python 中的反斜杠,則刪除最后一個字符

x = 'China\\' print(x.rstrip('\\'))
  • 執行結果:
China

十四、拆分字符串而不丟失拆分字符

import re string = 'China-Great-Country'print(re.split(r'(\-)', string))
  • 執行結果:
['China', '-', 'Great', '-', 'Country']

十五、從字符串 Python 中提取大寫和小寫字符

string = "asdfHRbySFss"uppers = [l for l in string if l.isupper()] print (''.join(uppers))lowers = [l for l in string if l.islower()] print (''.join(lowers))
  • 執行結果:
HRSF asdfbyss

十六、如何在 Python 中比較字符串的索引是否相等

myString = 'AAABBB' for idx, char in enumerate(myString, ):if idx + 1 == len(myString):breakif char == myString[idx + 1]:print(idx, char, myString[idx + 1])
  • 執行結果:
0 A A 1 A A 3 B B 4 B B

十七、在每個第 4 個字符上添加空格

string = 'Test5412Test8745Test' print([string[i:i + 4] for i in range(0, len(string), 4)])
  • 執行結果:
['Test', '5412', 'Test', '8745', 'Test']

十八、在 Python 中以多行方式連接字符串

str1 = "This is a demo string" str2 = "This is another demo string" strz = ("This is a line\n" +str1 + "\n" +"This is line 2\n" +str2 + "\n" +"This is line 3\n")print(strz)
  • 執行結果:
This is a line This is a demo string This is line 2 This is another demo string This is line 3

十九、在 Python 中將多個變量附加到列表中

volumeA = 100 volumeB = 20 volumeC = 10vol1 = [] vol2 = []vol1.extend((volumeA, volumeB, volumeC)) vol2 += [val for name, val in globals().items() if name.startswith('volume')]print(vol1) print(vol2)
  • 執行結果:
[100, 20, 10] [100, 20, 10]

二十、將字符串拆分為 Python 中的字符列表

s = 'China' l = list(s) print(l)
  • 執行結果:
['C', 'h', 'i', 'n', 'a']

二十一、如何在 Python 中小寫字符串

text = ['China', 'BEIJING']text = [txt.lower() for txt in text] print(text)
  • 執行結果:
['china', 'beijing']

二十二、通過多個標點符號分割字符串

import re s = 'a,b,c d!e.f\ncanada\tjapan&germany'l = re.split('[?.,\n\t&! ]', s)for i in l:print(i)
  • 執行結果:
a b c d e f canada japan germany

二十三、Python 字符串填充

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

二十四、在 Python 中檢查兩個字符串是否包含相同的字符

str1 = 'caars' str2 = 'rats' str3 = 'racs'print(set(str1)==set(str2)) print(set(str1)==set(str3))
  • 執行結果:
False True

二十五、在 Python 中查找給定字符串中的整個單詞

def contains_word(s, w):return (' ' + w + ' ') in (' ' + s + ' ')result = contains_word('those who seek shall find', 'find') print(result) result = contains_word('those who seek shall find', 'finds') print(result)
  • 執行結果:
True False

二十六、查找所有出現的子字符串

import reaString = 'this is a string where the substring "is" is repeated several times' print([(a.start(), a.end()) for a in list(re.finditer('is', aString))])
  • 執行結果:
[(2, 4), (5, 7), (38, 40), (42, 44)]

二十七、在 Python 中去除所有開頭在Python中的正斜杠上拆分字符串和結尾標點符號

from string import punctuation s = '.$958-5-China,#'print(s.strip(punctuation))
  • 執行結果:
958-5-Canada

二十八、用 Python 中的正斜杠上拆分字符串

s = 'China/Beijing/Tiananmen' l = s.split('/')print(l)
  • 執行結果:
['China', 'Beijing', 'Tiananmen']

二十九、根據 Python 中的索引位置將字符串大寫

def capitalize(s, ind):split_s = list(s)for i in ind:try:split_s[i] = split_s[i].upper()except IndexError:print('Index out of range : ', i)return "".join(split_s)print(capitalize("abracadabra", [2, 6, 9, 10, 50]))
  • 執行結果:
Index out of range : 50 abRacaDabRA

三十、檢查字符串中的所有字符是否都是 Python 中的數字

a = "1000" x = a.isdigit() print(x)b = "A1000" x = b.isdigit() print(x)
  • 執行結果:
True False

三十一、為什么使用’=='或’is’比較字符串有時會產生不同的結果

a = 'abcdef' b = ''.join(['ab', 'cd', 'ef']) 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)
  • 執行結果:
True False True False True

三十二、如何在 Python 中為字符串添加 X 個空格

print('China'.ljust(10) + 'Beijing'.ljust(20) + 'Tiananmen')
  • 執行結果:
China Beijing Tiananmen

三十三、如何在 Python 中替換字符串中的特定字符串實例

def nth_replace(str,search,repl,index):split = str.split(search,index+1)if len(split)<=index+1:return strreturn search.join(split[:-1])+repl+split[-1]str1 = "caars caars caars" str2 = nth_replace(str1, 'aa', 'a', 1)print(str2)
  • 執行結果:
caars cars caars

三十四、如何連接兩個變量,一個是字符串,另一個是 Python 中的 int

int1 = 10 str1 = 'test'print(str(int1) + str1)
  • 執行結果:
10test

三十五、在 Python 中的反斜杠上拆分字符串

s = r'China\Beijing\Tiananmen' l = s.split('\\')print(l)
  • 執行結果:
['r'China', 'Beijing', 'Tiananmen']

三十六、在 Python 中隨機大寫字符串中的字母

from random import choicex = "China Beijing Tiananmen" print(''.join(choice((str.upper, str.lower))(c) for c in x))
  • 執行結果:
ChiNA BeiJING TIANanMEn

三十七、在單詞處拆分字符串并且或不保留分隔符

import restring = "Canada AND Japan NOT Audi OR BMW"l = re.split(r'(AND|OR|NOT)', string) print(l)
  • 執行結果:
['Canada ', 'AND', ' Japan ', 'NOT', ' Audi ', 'OR', ' BMW']

三十八、在 Python 中填充 n 個字符

def header(txt: str, width=30, filler='*', align='c'):assert align in 'lcr'return {'l': txt.ljust, 'c': txt.center, 'r': txt.rjust}[align](width, filler)print(header("Canada")) print(header("Canada", align='l')) print(header("Canada", align='r'))
  • 執行結果:
************Canada************ Canada************************ ************************Canada

三十九、檢查變量是否等于一個字符串或另一個字符串

x = 'canada'if x in ['canada', 'japan', 'germany', 'australia']:print("Yes")
  • 執行結果:
true

四十、Python 字符串格式化固定寬度

num1 = 0.04154721841 num2 = 10.04154721841 num3 = 1002.04154721841print "{0:<12.11g}".format(num1)[:12] print "{0:<12.11g}".format(num2)[:12] print "{0:<12.11g}".format(num3)[:12]
  • 執行結果:
100.041549 0.04159874 12.8878877

四十一、在 Python 中查找字符串中字符的所有位置

test = 'canada#japan#uae' c = '#' print([pos for pos, char in enumerate(test) if char == c])
  • 執行結果:
[6, 12]

四十二、在 Python 中從左右修剪指定數量的空格

def trim(text, num_of_leading, num_of_trailing):text = list(text)for i in range(num_of_leading):if text[i] == " ":text[i] = ""else:breakfor i in range(1, num_of_trailing+1):if text[-i] == " ":text[-i] = ""else:breakreturn ''.join(text)txt1 = " Candada " print(trim(txt1, 1, 1)) print(trim(txt1, 2, 3)) print(trim(txt1, 6, 8))
  • 執行結果:
Candada Candada Candada

四十三、在 Python 中按字符串中字符的位置拆分字符串

str = 'canadajapan' splitat = 6 l, r = str[:splitat], str[splitat:] print(l) print(r)
  • 執行結果:
canada japan

四十四、將 Python 字符串中的第一個和最后一個字母大寫

string = "canada"result = string[0:1].upper() + string[1:-1].lower() + string[-1:].upper() print(result)
  • 執行結果:
CanadA

四十五、檢查字符串是否以 Python 中的給定字符串或字符結尾

txt = "Canada is a great country" x = txt.endswith("country") print(x)
  • 執行結果:
True

四十六、如何在 Python 中比較兩個字符串

str1 = "Canada" str2 = "Canada" print(str1 is str2) # True print(str1 == str2) # Truestring1 = ''.join(['Ca', 'na', 'da']) string2 = ''.join(['Can', 'ada']) print(string1 is string2) # False print(string1 == string2) # True
  • 執行結果:
True True False True

四十七、在 Python 中將整數格式化為帶有前導零的字符串

x = 4 x = str(x).zfill(5) print(x)
  • 執行結果:
00004

四十八、在 Python 中替換字符串的多個子字符串

s = "The quick brown fox jumps over the lazy dog" for r in (("brown", "red"), ("lazy", "quick")):s = s.replace(*r)print(s)
  • 執行結果:
The quick red fox jumps over the quick dog

四十九、Python 字符串替換字符

s = "The quick brown fox jumps over the lazy dog" for r in (("brown", "red"), ("lazy", "quick")):s = s.replace(*r)print(s)
  • 執行結果:
The quick red fox jumps over the quick dog

五十、在 Python 中查找字符串中所有出現的單詞的所有索引

import resentence = 'this is a sentence this this' word = 'this'for match in re.finditer(word, sentence):print(match.start(), match.end())
  • 執行結果:
0 4 19 23 24 28

五十一、在 Python 中將字符串中每個單詞的首字母大寫

import stringx = "they're bill's friends from the UK" x = string.capwords(x) print(x)x = x.title() print(x)
  • 執行結果:
They're Bill's Friends From The Uk They'Re Bill'S Friends From The Uk

五十二、僅在 Python 中的雙引號后拆分字符串

s = '"Canada", "Japan", "Germany", "Russia"' l = ['"{}"'.format(s) for s in s.split('"') if s not in ('', ', ')]for item in l:print(item)
  • 執行結果:
"Canada" "Japan" "Germany" "Russia"

五十三、在 Python 中以字節為單位獲取字符串的大小

string1 = "Canada" print(len(string1.encode('utf-16')))
  • 執行結果:
10

五十四、在 Python 中比較字符串中的字符

myString = 'AAABBB' for idx, char in enumerate(myString, ):if idx + 1 == len(myString):breakif char == myString[idx + 1]:print(idx, char, myString[idx + 1])
  • 執行結果:
0 A A 1 A A 3 B B 4 B B

五十五、在 Python 中的括號和字符串之間添加空格

import retest = "example(test)" test2 = "example(test)example" test3 = "(test)example" test4 = "example (test) example"for i in [test, test2, test3, test4]:print(re.sub(r"[^\S]?(\(.*?\))[^\S]?", r" \1 ", i).strip())
  • 執行結果:
example (test) example (test) example (test) example example (test) example

五十六、在 Python 中刪除開頭和結尾空格

s = ' China ' print(s.strip())
  • 執行結果:
China

五十七、在 Python 中拆分字符串以獲得第一個值

s = 'canada-japan-australia' l = s.split('-')[0] print(l)string = 'canada-japan-australia' print(string[:string.index('-')])
  • 執行結果:
canada canada

五十八、在 Python 中檢查字符串是大寫、小寫還是混合大小寫

words = ['The', 'quick', 'BROWN', 'Fox','jumped', 'OVER', 'the', 'Lazy', 'DOG'] print([word for word in words if word.islower()]) print([word for word in words if word.isupper()]) print([word for word in words if not word.islower() and not word.isupper()])
  • 執行結果:
['quick', 'jumped', 'the'] ['BROWN', 'OVER', 'DOG'] ['The', 'Fox', 'Lazy']

五十九、Python 計數字符串出現在給定字符串中

txt = "I love China, China is one of the most impressive countries in the world. China is a great country." x = txt.count("China") print(x)
  • 執行結果:
3

六十、在 Python3 中用前導零填充字符串

hour = 4 minute = 3print("{:0>2}:{:0>2}".format(hour, minute)) print("{:0>3}:{:0>5}".format(hour, minute)) print("{:0<3}:{:0<5}".format(hour, minute)) print("{:$<3}:{:#<5}".format(hour, minute))
  • 執行結果:
04:03 004:00003 400:30000 4$$:3####

六十一、在 Python 中檢查兩個字符串是否包含相同的字母和數字

from string import ascii_letters, digitsdef compare_alphanumeric(first, second):for character in first:if character in ascii_letters + digits and character not in second:return Falsereturn Truestr1 = 'ABCD' str2 = 'ACDB' print(compare_alphanumeric(str1, str2))str1 = 'A45BCD' str2 = 'ACD59894B' print(compare_alphanumeric(str1, str2))str1 = 'A45BCD' str2 = 'XYZ9887' print(compare_alphanumeric(str1, str2))
  • 執行結果:
True True False

六十二、在 Python 中的字符串中的字符之間添加空格的有效方法

s = "ABCDEF"print(" ".join(s)) print("-".join(s)) print(s.replace("", " ")[1: -1])
  • 執行結果:
A B C D E F A-B-C-D-E-F A B C D E F

六十三、在 Python 中查找字符串中最后一次出現的子字符串的索引

s = 'What is China famous for?'print(s.find('f')) print(s.index('f')) print(s.rindex('f')) print(s.rfind('f'))
  • 執行結果:
14 14 21 21

六十四、在 Python 中將字符串大寫

x = 'China' x = x.capitalize()print(x)
  • 執行結果:
China

六十五、拆分非字母數字并在 Python 中保留分隔符

import res = "65&Can-Jap#Ind^UK" l = re.split('([^a-zA-Z0-9])', s) print(l)
  • 執行結果:
['65', '&', 'Can', '-', 'Jap', '#', 'Ind', '^', 'UK']

六十六、計算 Python 中字符串中大寫和小寫字符的數量

string = "asdfHRbySFss"uppers = [l for l in string if l.isupper()] print(len(uppers))lowers = [l for l in string if l.islower()] print(len(lowers))
  • 執行結果:
4 8

六十七、在 Python 中將字符串與枚舉進行比較

from enum import Enum, autoclass Signal(Enum):red = auto()green = auto()orange = auto()def equals(self, string):return self.name == stringbrain_detected_colour = "red" print(Signal.red.equals(brain_detected_colour))brain_detected_colour = "pink" print(Signal.red.equals(brain_detected_colour))
  • 執行結果:
True False

六十八、Python 中的段落格式

import textwraphamlet = '''\ Lorum ipsum is the traditional Latin placeholder text, used when a designer needs a chunk of text for dummying up a layout. Journo Ipsum is like that, only using some of the most common catchphrases, buzzwords, and bon mots of the future-of-news crowd. Hit reload for a new batch. For entertainment purposes only.'''wrapper = textwrap.TextWrapper(initial_indent='\t' * 1,subsequent_indent='\t' * 2,width=40)for para in hamlet.splitlines():print(wrapper.fill(para))
  • 執行結果:
Lorum ipsum is the traditional Latinplaceholder text, used when a designerneeds a chunk of text for dummying upa layout.Journo Ipsum is like that, only usingsome of the most common catchphrases,buzzwords, and bon mots of the future-of-news crowd.Hit reload for a new batch. Forentertainment purposes only.

六十九、從 Python 中的某個索引替換字符

def nth_replace(str,search,repl,index):split = str.split(search,index+1)if len(split)<=index+1:return strreturn search.join(split[:-1])+repl+split[-1]str1 = "caars caars caars" str2 = nth_replace(str1, 'aa', 'a', 1)print(str2)
  • 執行結果:
caars cars caars

七十、如何連接 str 和 int 對象

i = 123 a = "foobar" s = a + str(i) print(s)
  • 執行結果:
foobar123

七十一、僅在 Python 中將字符串拆分為兩部分

s = 'canada japan australia' l = s.split(' ', 1) print(l)
  • 執行結果:
['canada', 'japan australia']

七十二、將大寫字符串轉換為句子大小寫

text = ['CANADA', 'JAPAN']text = [txt.capitalize() for txt in text] print(text)
  • 執行結果:
['Canada', 'Japan']

七十三、在標點符號上拆分字符串

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

七十四、在 Python 中比較字符串

str1 = "Canada" str2 = "Canada" print(str1 is str2) # True print(str1 == str2) # Truestring1 = ''.join(['Ca', 'na', 'da']) string2 = ''.join(['Can', 'ada']) print(string1 is string2) # False print(string1 == string2) # True
  • 執行結果:
True True False True

七十五、用零填充數字字符串

num = 123 print('{:<08d}'.format(num)) print('{:>08d}'.format(num))string = '123' print(string.ljust(8, '0')) print(string.rjust(8, '0'))print(string[::-1].zfill(8)[::-1])
  • 執行結果:
12300000 00000123 12300000 00000123 12300000

七十六、找到兩個字符串之間的差異位置

def dif(a, b):return [i for i in range(len(a)) if a[i] != b[i]]print(dif('stackoverflow', 'stacklavaflow'))
  • 執行結果:
[5, 6, 7, 8]

七十七、Python 填充字符串到固定長度

number = 4print(f'{number:05d}') # (since Python 3.6), or print('{:05d}'.format(number)) # orprint('{0:05d}'.format(number)) print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection) print(format(number, '05d'))
  • 執行結果:
00004 00004 00004 00004 00004 00004

七十八、Python 中的字符串查找示例

import retext = 'This is sample text to test if this pythonic '\'program can serve as an indexing platform for '\'finding words in a paragraph. It can give '\'values as to where the word is located with the '\'different examples as stated'find_the_word = re.finditer('as', text)for match in find_the_word:print('start {}, end {}, search string \'{}\''.format(match.start(), match.end(), match.group()))
  • 執行結果:
start 63, end 65, search string 'as' start 140, end 142, search string 'as' start 200, end 202, search string 'as'

七十九、刪除字符串中的開頭零和結尾零

list_num = ['000231512-n', '1209123100000-n00000','alphanumeric0000', '000alphanumeric']print([item.strip('0') for item in list_num]) # Remove leading + trailing '0' print([item.lstrip('0') for item in list_num]) # Remove leading '0' print([item.rstrip('0') for item in list_num]) # Remove trailing '0'
  • 執行結果:
['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric'] ['231512-n', '1209123100000-n00000', 'alphanumeric0000', 'alphanumeric'] ['000231512-n', '1209123100000-n', 'alphanumeric', '000alphanumeric']

八十、Python 在換行符上拆分

s = 'line 1\nline 2\nline without newline' l = s.splitlines(True)print(l)
  • 執行結果:
['line 1\n', 'line 2\n', 'line without newline']

八十一、將字符串中的每個第二個字母大寫

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

八十二、在 Python 中查找一個月的最后一個營業日或工作日

import calendardef last_business_day_in_month(year: int, month: int) -> int:return max(calendar.monthcalendar(year, month)[-1:][0][:5])print(last_business_day_in_month(2021, 1)) print(last_business_day_in_month(2021, 2)) print(last_business_day_in_month(2021, 3)) print(last_business_day_in_month(2021, 4)) print(last_business_day_in_month(2021, 5))
  • 執行結果:
29 26 31 30 31

八十三、比較兩個字符串中的單個字符

def compare_strings(a, b):result = Trueif len(a) != len(b):print('string lengths do not match!')for i, (x, y) in enumerate(zip(a, b)):if x != y:print(f'char miss-match {x, y} in element {i}')result = Falseif result:print('strings match!')return result print(compare_strings("canada", "japan"))
  • 執行結果:
string lengths do not match! char miss-match ('c', 'j') in element 0 char miss-match ('n', 'p') in element 2 char miss-match ('d', 'n') in element 4 False

八十四、在 Python 中多次顯示字符串

print('canada' * 3) print(*3 * ('canada',), sep='-')
  • 執行結果:
canadacanadacanada canada-canada-canada

八十五、Python 從頭開始替換字符串

def nth_replace(s, old, new, occurrence):li = s.rsplit(old, occurrence)return new.join(li)str1 = "caars caars caars caars caars" str2 = nth_replace(str1, 'aa', 'a', 1) print(str2)str2 = nth_replace(str1, 'aa', 'a', 2) print(str2)str2 = nth_replace(str1, 'aa', 'a', 3) print(str2)
  • 執行結果:
caars caars caars caars cars caars caars caars cars cars caars caars cars cars cars

八十六、在 Python 中連接字符串和變量值

year = '2020'print('test' + str(year)) print('test' + year.__str__())
  • 執行結果:
test2020 test2020

八十七、在每個下劃線處拆分字符串并在第 N 個位置后停止

s = 'canada_japan_australia_us_uk' l = s.split('_', 0) print(l)l = s.split('_', 1) print(l)l = s.split('_', 2) print(l)
  • 執行結果:
['canada_japan_australia_us_uk'] ['canada', 'japan_australia_us_uk'] ['canada', 'japan', 'australia_us_uk']

八十八、Python 中列表中第一個單詞的首字母大寫

text = ['johnny rotten', 'eddie vedder', 'kurt kobain','chris cornell', 'micheal phillip jagger']text = [txt.capitalize() for txt in text] print(text)
  • 執行結果:
['Johnny rotten', 'Eddie vedder', 'Kurt kobain', 'Chris cornell', 'Micheal phillip jagger']

八十九、如何在 Python 字符串中找到第一次出現的子字符串

test = 'Position of a character' print(test.find('of')) print(test.find('a'))
  • 執行結果:
9 12

九十、不同長度的 Python 填充字符串

data = [1148, 39, 365, 6, 56524]for element in data:print("{:>5}".format(element))
  • 執行結果:
1148393656 56524

九十一、Python 比較兩個字符串保留一端的差異

def after(s1, s2):index = s1.find(s2)if index != -1 and index + len(s2) < len(s1):return s1[index + len(s2):]else:return Nones1 = "canada" s2 = "can"print(after(s1, s2))
  • 執行結果:
ada

九十二、如何用 Python 中的一個字符替換字符串中的所有字符

test = 'canada' print('$' * len(test))
  • 執行結果:
$$$$$$

九十三、在字符串中查找子字符串并在 Python 中返回子字符串的索引

def find_str(s, char):index = 0if char in s:c = char[0]for ch in s:if ch == c:if s[index:index + len(char)] == char:return indexindex += 1return -1print(find_str("India Canada Japan", "Canada")) print(find_str("India Canada Japan", "cana")) print(find_str("India Canada Japan", "Uae"))
  • 執行結果:
6 -1 -1

九十四、從 Python 中的字符串中修剪特定的開頭和結尾字符

number = '+91 874854778'print(number.strip('+')) print(number.lstrip('+91'))
  • 執行結果:
91 874854778874854778

九十五、在 Python 中按長度將字符串拆分為字符串

string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"x = 3 res = [string[y - x:y] for y in range(x, len(string) + x, x)] print(res)
  • 執行結果:
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ']

九十六、如何在 Python 中將字符串的第三個字母大寫

s = "xxxyyyzzz"# convert to list a = list(s)# change every third letter in place with a list comprehension a[2::3] = [x.upper() for x in a[2::3]]# back to a string s = ''.join(a)print(s)
  • 執行結果:
xxXyyYzzZ

九十七、將制表符大小設置為指定的空格數

txt = "Canada\tis\ta\tgreat\tcountry"print(txt) print(txt.expandtabs()) print(txt.expandtabs(2)) print(txt.expandtabs(4)) print(txt.expandtabs(10))
  • 執行結果:
Canada is a great country Canada is a great country Canada is a great country Canada is a great country Canada is a great country

九十八、將兩個字符串與某些字符進行比較

str1 = "Can" str2 = "Canada" print(str1 in str2) print(str1.startswith(str2)) print(str2.startswith(str1))print(str1.endswith(str2))str3 = "CAN" print(str3 in str2)
  • 執行結果:
True False True False False

九十九、字符串格式化填充負數

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

一百、單獨替換字符串中的第一個字符

str1 = "caars caars caars" str2 = str1.replace('aa', 'a', 1)print(str2)
  • 執行結果:
cars caars caars

一百零一、連接固定字符串和變量

variable = 'Hello' print('This is the Test File ' + variable)variable = '10' print('This is the Test File ' + str(variable))
  • 執行結果:
This is the Test File Hello This is the Test File 10

一百零二、將字符串拆分為多個字符串

s = 'str1, str2, str3, str4' l = s.split(', ')print(l)
  • 執行結果:
['str1', 'str2', 'str3', 'str4']

一百零三、在 Python 中將字符串大寫

x = "canada japan australia"x = x[:1].upper() + x[1:] print(x)x= x.capitalize() print(x)x= x.title() print(x)
  • 執行結果:
Canada japan australia Canada japan australia Canada Japan Australia

一百零四、將字節字符串拆分為單獨的字節

data = b'\x00\x00\x00\x00\x00\x00'info = [data[i:i + 2] for i in range(0, len(data), 2)] print(info)
  • 執行結果:
[b'\x00\x00', b'\x00\x00', b'\x00\x00']

一百零五、用空格填寫 Python 字符串

string = 'Hi'.ljust(10) print(string)string = 'Hi'.rjust(10) print(string)string = '{0: ^20}'.format('Hi') print(string)string = '{message: >16}'.format(message='Hi') print(string)string = '{message: <16}'.format(message='Hi') print(string)string = '{message: <{width}}'.format(message='Hi', width=20) print(string)
  • 執行結果:
Hi HiHi Hi Hi Hi

一百零六、比較兩個字符串并檢查它們共有多少個字符

from collections import Counterdef shared_chars(s1, s2):return sum((Counter(s1) & Counter(s2)).values())print(shared_chars('car', 'carts'))
  • 執行結果:
3

一百零七、在 Python 中的數字和字符串之間添加空格

import res = "ABC24.00XYZ58.28PQR" s = re.sub("[A-Za-z]+", lambda group: " " + group[0] + " ", s) print(s.strip())
  • 執行結果:
ABC 24.00 XYZ 58.28 PQR

一百零八、如何在 Python 中去除空格

s = ' canada ' print(s.rstrip()) # For whitespace on the right side use rstrip. print(s.lstrip()) # For whitespace on the left side lstrip. print(s.strip()) # For whitespace from both side.s = ' \t canada ' 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.
  • 執行結果:
canada canada canadacanada

一百零九、字符串中最后一次出現的分隔符處拆分字符串

s = 'canada-japan-australia-uae-india' l = s.rsplit('-', 1)[1] print(l)
  • 執行結果:
india

一百一十、在 Python 中將字符串的最后一個字母大寫

string = "canada"result = string[:-1] + string[-1].upper() print(result)result = string[::-1].title()[::-1] print(result)
  • 執行結果:
canadA canadA

一百一十一、使用指定字符居中對齊字符串

txt = "canada" x = txt.center(20) print(x)
  • 執行結果:
canada

一百一十二、格式字符串中動態計算的零填充

x = 4 w = 5 print('{number:0{width}d}'.format(width=w, number=x))
  • 執行結果:
00004

一百一十三、在 Python 中使用 string.replace()

a = "This is the island of istanbul" print (a.replace("is" , "was", 1)) print (a.replace("is" , "was", 2)) print (a.replace("is" , "was"))
  • 執行結果:
Thwas is the island of istanbul Thwas was the island of istanbul Thwas was the wasland of wastanbul

一百一十四、在 Python 中獲取字符的位置

test = 'Position of a character' print(test.find('of')) print(test.find('a'))
  • 執行結果:
9 12

一百一十五、Python 字符串替換多次出現

s = "The quick brown fox jumps over the lazy dog" for r in (("brown", "red"), ("lazy", "quick")):s = s.replace(*r)print(s)
  • 執行結果:
The quick red fox jumps over the quick dog

一百一十六、在索引后找到第一次出現的字符

string = 'This + is + a + string' x = string.find('+', 4) print(x)x = string.find('+', 10) print(x)
  • 執行結果:
5 10

一百一十七、在 Python 中將字符串更改為大寫

x = 'canada' x = x.upper()print(x)
  • 執行結果:
CANADA

一百一十八、在 Python 中拆分具有多個分隔符的字符串

import rel = re.split(r'[$-]+', 'canada$-india$-japan$-uae') print(l)
  • 執行結果:
['canada', 'india', 'japan', 'uae']

一百一十九、在 Python 中獲取字符串的大小

string1 = "Canada" print(len(string1))string2 = " Canada" print(len(string2))string3 = "Canada " print(len(string3))
  • 執行結果:
6 8 8

一百二十、Python 中的字符串比較 is vs ==

x = 'canada' y = ''.join(['ca', 'na', 'da']) print(x == y) print(x is y)x = [1, 2, 3] y = [1, 2, 3] print(x == y) print(x is y)z = y print(z is y)
  • 執行結果:
True False True False True

一百二十一、每當數字與非數字相鄰時,Python 正則表達式都會添加空格

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

一百二十二、在 Python 中僅按第一個空格拆分字符串

s = 'canada japan australia' l = s.split(' ', 1) print(l)
  • 執行結果:
['canada', 'japan australia']

一百二十三、在 Python 中將字符串中的一些小寫字母更改為大寫

indices = set([0, 7, 14, 18])s = "i love China" print("".join(c.upper() if i in indices else c for i, c in enumerate(s)))
  • 執行結果:
I love China

一百二十四、將字符串拆分為具有多個單詞邊界分隔符的單詞

import rethestring = "a,b,c d!e.f\ncanada\tjapan&germany" listitems = re.findall('\w+', thestring)for item in listitems:print(item)
  • 執行結果:
a b c d e f canada japan germany

一百二十五、檢查一個字符串在 Python 中是否具有相同的字符

str1 = 'caars' str2 = 'rats' str3 = 'racs'print(set(str1)==set(str2)) print(set(str1)==set(str3))
  • 執行結果:
False True

一百二十六、在多個分隔符或指定字符上拆分字符串

import restring_test = "Ethnic (279), Responses (3), 2016 Census - 25% Sample" print(re.findall(r"[\w']+", string_test))def split_by_char(s, seps):res = [s]for sep in seps:s, res = res, []for seq in s:res += seq.split(sep)return resprint(split_by_char(string_test, [' ', '(', ')', ',']))
  • 執行結果:
['Ethnic', '279', 'Responses', '3', '2016', 'Census', '25', 'Sample'] ['Ethnic', '', '279', '', '', 'Responses', '', '3', '', '', '2016', 'Census', '-', '25%', 'Sample']

一百二十七、將一個字符串附加到另一個字符串

# Example 1 str1 = "Can" str2 = "ada" str3 = str1 + str2 print(str3)# Example 2 str4 = 'Ca' str4 += 'na' str4 += 'da' print(str4)# Example 3 join_str = "".join((str1, str2)) print(join_str)# Example 4 str_add = str1.__add__(str2) print(str_add)
  • 執行結果:
Canada Canada Canada Canada

一百二十八、在 Python 中遍歷字符串

# Example 1 test_str = "Canada" for i, c in enumerate(test_str):print(i, c)print("------------------------")# Example 2 indx = 0 while indx < len(test_str):print(indx, test_str[indx])indx += 1print("------------------------") # Example 3 for char in test_str:print(char)
  • 執行結果:
0 C 1 a 2 n ....... d a

一百二十九、從 Python 中的字符串中去除標點符號

import string import re# Example 1 s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample" out = re.sub(r'[^\w\s]', '', s) print(out)# Example 2 s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample" for p in string.punctuation:s = s.replace(p, "") print(s)# Example 3 s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample" out = re.sub('[%s]' % re.escape(string.punctuation), '', s) print(out)
  • 執行結果:
Ethnic 279 Responses 3 2016 Census 25 Sample Ethnic 279 Responses 3 2016 Census 25 Sample Ethnic 279 Responses 3 2016 Census 25 Sample

一百三十、將列表轉換為字符串

list_exp = ['Ca', 'na', 'da'] print(type(list_exp))# Example 1 str_exp1 = ''.join(list_exp) print(type(str_exp1)) print(str_exp1)# Example 2 str_exp2 = ''.join(str(e) for e in list_exp) print(type(str_exp2)) print(str_exp2)# Example 3 str_exp3 = ''.join(map(str, list_exp)) print(type(str_exp2)) print(str_exp2)
  • 執行結果:
class 'list' class 'str' Canada class 'str' Canada class 'str' Canada

一百三十一、將 JSON 轉換為字符串

import json# list with dict a simple Json format json_exp = \[{"id": "12", "name": "Mark"}, {"id": "13", "name": "Rock", "date": None}] print(type(json_exp))str_conv = json.dumps(json_exp) # string print(type(str_conv)) print(str_conv)
  • 執行結果:
class 'list'class 'str'[{"id": "12", "name": "Mark"}, {"id": "13", "name": "Rock", "date": null}]

一百三十二、對字符串列表進行排序

# Example 1 str_list = ["Japan", "Canada", "Australia"] print(str_list) str_list.sort() print(str_list)# Example 2 str_list = ["Japan", "Canada", "Australia"] for x in sorted(str_list):print(x)# Example 3 str_var = "Canada" strlist = sorted(str_var) print(strlist)
  • 執行結果:
['Japan', 'Canada', 'Australia'] ['Australia', 'Canada', 'Japan'] Australia Canada Japan ['C', 'a', 'a', 'a', 'd', 'n']

一百三十三、在 Python 中檢查字符串是否以 XXXX 開頭

import reexp_str = "Python Programming"# Example 1 if re.match(r'^Python', exp_str):print(True) else:print(False)# Example 2 result = exp_str.startswith("Python") print(result)
  • 執行結果:
True True

一百三十四、在 Python 中將兩個字符串網格或交錯在一起的不同方法

str1 = "AAAA" str2 = "BBBBBBBBB"# Example 1 mesh = "".join(i + j for i, j in zip(str1, str2)) print("Example 1:", mesh)# Example 2 min_len = min(len(str1), len(str2)) mesh = [''] * min_len * 2 mesh[::2] = str1[:min_len] mesh[1::2] = str2[:min_len] print("Example 2:", ''.join(mesh))# Example 3 mesh = ''.join(''.join(item) for item in zip(str1, str2)) print("Example 3:", mesh)# Example 4 min_len = min(len(str1), len(str2)) mesh = [''] * min_len * 2 mesh[::2] = str1[:min_len] mesh[1::2] = str2[:min_len] mesh += str1[min_len:] + str2[min_len:] print("Example 4:", ''.join(mesh))
  • 執行結果:
Example 1: ABABABAB Example 2: ABABABAB Example 3: ABABABAB Example 4: ABABABABBBBBB

總結

以上是生活随笔為你收集整理的Python之字符串的134个常用操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。