## 字符串切片操作
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.