python字符串操作入门十八讲——合集一

Posted 肥学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python字符串操作入门十八讲——合集一相关的知识,希望对你有一定的参考价值。

字符串操作十八讲合集

导读


之前都是一讲一篇的总结,感觉不过瘾这次来点猛的。

🍀第三讲-向字符串填充或添加零的不同方法

num = 7
 
print('0:0>5d'.format(num))  # left
print('0:0<5d'.format(num))  # right
 
print(':05d'.format(num))
 
print("%0*d" % (5, num))
print(format(num, "05d"))
 
temp = 'test'
print(temp.rjust(10, '0'))
print(temp.ljust(10, '0'))
Output:

00007

70000

00007

00007

00007

000000test

test000000

🍀第四讲—将 String 变量转换为 float、int 或 boolean

String to Float

float_string = "254.2511"
print(type(float_string))
 
string_to_float = float(float_string)
print(type(string_to_float))

String to Integer

int_string = "254"
print(type(int_string))
 
string_to_int = int(int_string)
print(type(string_to_int))

String to Boolean

bool_string = "True"
print(type(bool_string))
 
string_to_bool = bool(bool_string)
print(type(string_to_bool))
Output:

class 'str'

class 'float>

class 'str'

class 'int'

class 'str'

class 'bool'

🍀第五讲-去掉字符串中的 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)

Output:

  	 a string example

 

 

a string example

 

 

  	 a string example

a string example

🍀第六讲-生成N个字符的随机字符串

import string
import random
 
 
def string_generator(size):
    chars = string.ascii_uppercase + string.ascii_lowercase
    return ''.join(random.choice(chars) for _ in range(size))
 
 
def string_num_generator(size):
    chars = string.ascii_lowercase + string.digits
    return ''.join(random.choice(chars) for _ in range(size))
 
 

Random String

test = string_generator(10)
print(test)
 

Random String and Number

test = string_num_generator(15)
print(test)
Output:

acpPTojXet

qmpah72cjb83eqd
以不同的方式反转字符串
test_string = 'Python Programming'
 
string_reversed = test_string[-1::-1]
print(string_reversed)
 
string_reversed = test_string[::-1]
print(string_reversed)
 

🍀第七讲-反转字符串

a="shdfka"
for i in reversed(a):
    print(i,end="")
    
Output:

akfdhs

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

import re
 
 
def convert(oldstring):
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', oldstring)
    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()
 
 

Camel Case to Snake Case

print(convert('CamelCase'))
print(convert('CamelCamelCase'))
print(convert('getHTTPResponseCode'))
print(convert('get2HTTPResponseCode'))

改变 Case 的特征

text = "python programming"
result = text[:1].upper() + text[1:7].lower() \\
    + text[7:8].upper() + text[8:].lower()
print(result)
 
text = "Kilometer"
print(text.lower())
 
old_string = "hello python"
new_string = old_string.capitalize()
print(new_string)
 
old_string = "Hello Python"
new_string = old_string.swapcase()
print(new_string)
Output:

camel_case

camel_camel_case

get_http_response_code

get2_http_response_code

Python Programming

kilometer

Hello python

hELLO pYTHON

🍀第九讲-检查给定的字符串是否是 Python 中的回文字符串

import re
 
 
Continue = 1
Quit = 2
 
 
def main():
    choice = 0
 
    while choice != Quit:
        # Display the menu.
        display_menu()
        # Constant to assume string is Palindrome
        is_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 = False
 
            if 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()
Output:

*******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 test
 
for str_item in str_list:
    if str_test.endswith(str_item):
        print("found")
        break   # loop ends when result found
    else:
        print("not found")
Output:

not found

not found

found

🍀第十一讲-在字符串中应用查找模式

import re

s1 = '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) + 1
        else:
            regex.append('\\\\%d' % nr[c])
    return bool(re.match(''.join(regex) + '$', s))


print(match(s1, p))
print(match(s2, p))
print(match(s3, p))
Output:

True
False
True

🍀第十二讲-如果是 Python 中的反斜杠,则删除最后一个字符

x = 'Canada\\\\'
print(x.rstrip('\\\\'))
Output:

Canada
在Python中拆分字符串而不丢失拆分字符
import re
string = 'canada-japan-india'

print(re.split(r'(\\-)', string))
Output:

['canada', '-', 'japan', '-', 'india']
从字符串 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))
Output:

HRSF
asdfbyss

🍀第十三讲-如何在 Python 中比较字符串的索引是否相等

myString = 'AAABBB'
for idx, char in enumerate(myString, ):
    if idx + 1 == len(myString):
        break
    if char == myString[idx + 1]:
        print(idx, char, myString[idx + 1])
Output:

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)])
Output:

['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)
Output:

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 = 10

vol1 = []
vol2 = []

vol1.extend((volumeA, volumeB, volumeC))
vol2 += [val for name, val in globals().items() if name.startswith('volume')]

print(vol1)
print(vol2)
Output:

[100, 20, 10]
[100, 20, 10]

🍀第十六讲-将字符串拆分为 Python 中的字符列表

s = 'canada'
l = list(s)
print(l)
Output:

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

🍀第十七讲-如何在 Python 中小写字符串

text = ['Canada', 'JAPAN']

text = [txt.lower() for txt in text]
print(text)
Output:

['canada', 'japan']

🍀第十八讲-通过多个标点符号分割字符串

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

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)
    )
Output:

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))
Output:

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)
Output:

True
False

🍀第二十二讲-查找所有出现的子字符串

import re

aString = '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))])
Output:

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

🍀第二十三讲-在 Python 中去除所有开头在Python中的正斜杠上拆分字符串和结尾标点符号

from string import punctuation
s = '.$958-5-Canada,#'

print(s.strip(punctuation))
Output:

958-5-Canada

🍀第二十四讲-用 Python 中的正斜杠上拆分字符串

s = 'canada/japan/australia'
l = s.split('/')
 
print(l)
Output:

['canada', 'japan', 'australia']

🍀第二十五讲-根据 Python 中的索引位置将字符串大写

def capitalize(s, ind):
    split_s = list(s)
    for i in ind:
        try:
            split_s[ipython字符串操作入门十八讲——合集一

字符串入门十八讲合集四

字符串入门十八讲合集四

python入门十八讲——第一讲(字符串切片操作)

python入门十八讲——第二讲(计算字符串中字符出现次数的多种方法)

学习自然语言处理技术:第十八讲 义位