整理了10个Python字符串常用操作,不看就亏了(一)

## 字符串切片操作

test = "Python Programming"
print("String: ", test)
 
# First one character
first_character = test[:1]
print("First Character: ", first_character)
 
# Last one character
last_character = test[-1:]
print("Last Character: ", last_character)
 
# Everything except the first one character
except_first = test[1:]
print("Except First Char.: ", except_first)
 
# Everything except the last one character
except_last = test[:-1]
print("Except First Char.: ", except_last)
 
# Everything between first and last two character
between_two = test[2:-2]
print("Between two character: ", between_two)
 
# Skip one character
skip_one = test[0:18:2]  # [start:stop:step]
print("Skip one character: ", skip_one)
 
# Reverse String
reverse_str = test[::-1]
print("Reverse String: ", reverse_str)

Output:

String:  Python Programming

First Character:  P

Last Character:  g

Except First Char.:  ython Programming

Except First Char.:  Python Programmin

Between two character:  thon Programmi

Skip one character:  Pto rgamn

Reverse String:  gnimmargorP nohtyP

检查字符串是否为空

import re
from collections import Counter
 
sentence = 'Canada is located in the northern part of North America'
# Example I
counter = len(re.findall("a", sentence))
print(counter)
 
# Example II
counter = sentence.count('a')
print(counter)
 
# Example III
counter = Counter(sentence)
print(counter['a'])

Output:

Empty

Empty

Empty

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

import re
from collections import Counter
 
sentence = 'Canada is located in the northern part of North America'
# Example I
counter = len(re.findall("a", sentence))
print(counter)
 
# Example II
counter = sentence.count('a')
print(counter)
 
# Example III
counter = Counter(sentence)
print(counter['a'])
Output:

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

Output:

class 'str'

class 'float>

class 'str'

class 'int'

class 'str'

class 'bool'

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

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

Output:

00007

70000

00007

00007

00007

000000test

test000000

去掉字符串中的 space 字符

string_var = "  \t a string example\n\t\r  "
print(string_var)
 
string_var = string_var.lstrip()  # trim white space from left
print(string_var)
 
string_var = "  \t a string example\t  "
string_var = string_var.rstrip()  # trim white space from right
print(string_var)
 
string_var = "  \t a string example\t  "
string_var = string_var.strip()  # trim white space from both side
print(string_var)

Output:

    a string example

 

 

a string example

 

 

    a string example

a string example

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

import string
import random
 
 
def string_generator(size):
    chars = string.ascii_uppercase + string.ascii_lowercase
    return ''.join(random.choice(chars) for _ in range(size))
 
 
def string_num_generator(size):
    chars = string.ascii_lowercase + string.digits
    return ''.join(random.choice(chars) for _ in range(size))
 
 
# Random String
test = string_generator(10)
print(test)
 
# Random String and Number
test = string_num_generator(15)
print(test)

Output:

acpPTojXet

qmpah72cjb83eqd

以不同的方式反转字符串

test_string = 'Python Programming'
 
string_reversed = test_string[-1::-1]
print(string_reversed)
 
string_reversed = test_string[::-1]
print(string_reversed)
 
 
# String reverse logically
def string_reverse(text):
    r_text = ''
    index = len(text) - 1
 
    while index >= 0:
        r_text += text[index]
        index -= 1
 
    return r_text
 
print(string_reverse(test_string))

Output:

gnimmargorP nohtyP

gnimmargorP nohtyP

gnimmargorP nohtyP

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

import re
 
 
def convert(oldstring):
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', oldstring)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
 
 
# Camel Case to Snake Case
print(convert('CamelCase'))
print(convert('CamelCamelCase'))
print(convert('getHTTPResponseCode'))
print(convert('get2HTTPResponseCode'))
 
# Change Case of a particular character
text = "python programming"
result = text[:1].upper() + text[1:7].lower() \
    + text[7:8].upper() + text[8:].lower()
print(result)
 
text = "Kilometer"
print(text.lower())
 
old_string = "hello python"
new_string = old_string.capitalize()
print(new_string)
 
old_string = "Hello Python"
new_string = old_string.swapcase()
print(new_string)

Output:

camel_case

camel_camel_case

get_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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值