在 Python3 中用前导零填充字符串
hour = 4 minute = 3 print("{: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))
Output:
04:03 004:00003 400:30000 4$$:3####
在 Python 中检查两个字符串是否包含相同的字母和数字
from string import ascii_letters, digits def compare_alphanumeric(first, second): for character in first: if character in ascii_letters + digits and character not in second: return False return True str1 = '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))
Output:
True True False
在Python中的字符串中的字符之间添加空格的有效方法
s = "CANADA" print(" ".join(s)) print("-".join(s)) print(s.replace("", " ")[1: -1])
Output:
C A N A D A C-A-N-A-D-A C A N A D A
在Python中查找字符串中最后一次出现的子字符串的索引
s = 'What is Canada famous for?' print(s.find('f')) print(s.index('f')) print(s.rindex('f')) print(s.rfind('f'))
Output:
15 15 22 22
在 Python 中将字符串大写
x = 'canada' x = x.capitalize() print(x)
Output:
Canada
拆分非字母数字并在 Python 中保留分隔符
import re s = "65&Can-Jap#Ind^UK" l = re.split('([^a-zA-Z0-9])', s) print(l)
Output:
['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))
Output:
4 8
在 Python 中将字符串与枚举进行比较
from enum import Enum, auto class Signal(Enum): red = auto() green = auto() orange = auto() def equals(self, string): return self.name == string brain_detected_colour = "red" print(Signal.red.equals(brain_detected_colour)) brain_detected_colour = "pink" print(Signal.red.equals(brain_detected_colour))
Output:
True False
Python中的段落格式
import textwrap hamlet = '''\ 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))
Output:
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.
从 Python 中的某个索引替换字符
def nth_replace(str,search,repl,index): split = str.split(search,index+1) if len(split)<=index+1: return str return search.join(split[:-1])+repl+split[-1] str1 = "caars caars caars" str2 = nth_replace(str1, 'aa', 'a', 1) print(str2)
Output:
caars cars caars
如何连接 str 和 int 对象
i = 123 a = "foobar" s = a + str(i) print(s)
Output:
foobar123
仅在 Python 中将字符串拆分为两部分
s = 'canada japan australia' l = s.split(' ', 1) print(l)
Output:
['canada', 'japan australia']
将大写字符串转换为句子大小写
text = ['CANADA', 'JAPAN'] text = [txt.capitalize() for txt in text] print(text)
Output:
['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)
Output:
a b c d e f canada japan germany
在 Python 中比较字符串
str1 = "Canada" str2 = "Canada" print(str1 is str2) # True print(str1 == str2) # True string1 = ''.join(['Ca', 'na', 'da']) string2 = ''.join(['Can', 'ada']) print(string1 is string2) # False print(string1 == string2) # True
Output:
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])
Output:
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'))
Output:
[5, 6, 7, 8]
Python填充字符串到固定长度
number = 4 print(f'{number:05d}') # (since Python 3.6), or print('{:05d}'.format(number)) # or print('{0:05d}'.format(number)) print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection) print(format(number, '05d'))
Output:
00004 00004 00004 00004 00004 00004
Python中的字符串查找示例
import re text = '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()))
Output:
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'
Output:
['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)
Output:
['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)
Output:
cAnAdA
在 Python 中查找一个月的最后一个营业日或工作日
import calendar def 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))
Output:
29 26 31 30 31
比较两个字符串中的单个字符
def compare_strings(a, b): result = True if 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 = False if result: print('strings match!') return result print(compare_strings("canada", "japan"))
Output:
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='-')
Output:
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)
Output:
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__())
Output:
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)
Output:
['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)
Output:
['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'))
Output:
9 12
不同长度的Python填充字符串
data = [1148, 39, 365, 6, 56524] for element in data: print("{:>5}".format(element))
Output:
1148 39 365 6 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 None s1 = "canada" s2 = "can" print(after(s1, s2))
Output:
ada
如何用Python中的一个字符替换字符串中的所有字符
test = 'canada' print('$' * len(test))
Output:
$$$$$$
在字符串中查找子字符串并在 Python 中返回子字符串的索引
def find_str(s, char): index = 0 if char in s: c = char[0] for ch in s: if ch == c: if s[index:index + len(char)] == char: return index index += 1 return -1 print(find_str("India Canada Japan", "Canada")) print(find_str("India Canada Japan", "cana")) print(find_str("India Canada Japan", "Uae"))
Output:
6 -1 -1
从 Python 中的字符串中修剪特定的开头和结尾字符
number = '+91 874854778' print(number.strip('+')) print(number.lstrip('+91'))
Output:
91 874854778 874854778
在 Python 中按长度将字符串拆分为字符串
string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" x = 3 res = [string[y - x:y] for y in range(x, len(string) + x, x)] print(res)
Output:
['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)
Output:
xxXyyYzzZ
将制表符大小设置为指定的空格数
txt = "Canada\tis\ta\tgreat\tcountry" print(txt) print(txt.expandtabs()) print(txt.expandtabs(2)) print(txt.expandtabs(4)) print(txt.expandtabs(10))
Output:
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)
Output:
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)
Output:
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)
Output:
cars caars caars
连接固定字符串和变量
variable = 'Hello' print('This is the Test File ' + variable) variable = '10' print('This is the Test File ' + str(variable))
Output:
This is the Test File Hello This is the Test File 10
将字符串拆分为多个字符串
s = 'str1, str2, str3, str4' l = s.split(', ') print(l)
Output:
['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)
Output:
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)
Output:
[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)
Output:
Hi Hi Hi Hi Hi Hi
比较两个字符串并检查它们共有多少个字符
from collections import Counter def shared_chars(s1, s2): return sum((Counter(s1) & Counter(s2)).values()) print(shared_chars('car', 'carts'))
Output:
3
在 Python 中的数字和字符串之间添加空格
import re s = "ABC24.00XYZ58.28PQR" s = re.sub("[A-Za-z]+", lambda group: " " + group[0] + " ", s) print(s.strip())
Output:
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.
Output:
canada canada canada canada
字符串中最后一次出现的分隔符处拆分字符串
s = 'canada-japan-australia-uae-india' l = s.rsplit('-', 1)[1] print(l)
Output:
india
在Python中将字符串的最后一个字母大写
string = "canada" result = string[:-1] + string[-1].upper() print(result) result = string[::-1].title()[::-1] print(result)
Output:
canadA canadA
使用指定字符居中对齐字符串
txt = "canada" x = txt.center(20) print(x)
Output:
canada
格式字符串中动态计算的零填充
x = 4 w = 5 print('{number:0{width}d}'.format(width=w, number=x))
Output:
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"))
Output:
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'))
Output:
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)
Output:
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)
Output:
5 10
在 Python 中将字符串更改为大写
x = 'canada' x = x.upper() print(x)
Output:
CANADA
在 Python 中拆分具有多个分隔符的字符串
import re l = re.split(r'[$-]+', 'canada$-india$-japan$-uae') print(l)
Output:
['canada', 'india', 'japan', 'uae']
在 Python 中获取字符串的大小
string1 = "Canada" print(len(string1)) string2 = " Canada" print(len(string2)) string3 = "Canada " print(len(string3))
Output:
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)
Output:
True False True False True
每当数字与非数字相邻时,Python 正则表达式都会添加空格
import re text = ['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)))
Output:
'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)
Output:
['canada', 'japan australia']
在Python中将字符串中的一些小写字母更改为大写
indices = set([0, 7, 14, 18]) s = "i love canada and japan" print("".join(c.upper() if i in indices else c for i, c in enumerate(s)))
Output:
I love Canada And Japan
将字符串拆分为具有多个单词边界分隔符的单词
import re thestring = "a,b,c d!e.f\ncanada\tjapan&germany" listitems = re.findall('\w+', thestring) for item in listitems: print(item)
Output:
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))
Output:
False True
在多个分隔符或指定字符上拆分字符串
import re string_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 res print(split_by_char(string_test, [' ', '(', ')', ',']))
Output:
['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)
Output:
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 += 1 print("------------------------") # Example 3 for char in test_str: print(char)
Output:
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)
Output:
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)
Output:
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)
Output:
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)
Output:
['Japan', 'Canada', 'Australia'] ['Australia', 'Canada', 'Japan'] Australia Canada Japan ['C', 'a', 'a', 'a', 'd', 'n']
在 Python 中检查字符串是否以 XXXX 开头
import re exp_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)
Output:
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))
Output:
Example 1: ABABABAB Example 2: ABABABAB Example 3: ABABABAB Example 4: ABABABABBBBBB