程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python basics] built in data structure - use of string

編輯:Python

The use of strings

  • One 、 Common escape symbols
  • Two 、 The basic characteristics of strings
  • 3、 ... and 、 practice
  • Four 、 String judgment and conversion
  • 5、 ... and 、 String search and Statistics
  • 6、 ... and 、 Exercises

One 、 Common escape symbols


1、 Line break

2、 Indicator tab

Two 、 The basic characteristics of strings

1、 Join operator and repeat operator
Join operators :

print('hello '+'westos')
hello westos

Repeat characters

print('*'*50+' Student management system '+'*'*50)
************************************************** Student management system **************************************************

2、 Member operators
Judge yes or no

s= 'hello westos'
print('westos' in s)
print('westos' not in s)
# result 
True
False

3、 Indexes
Forward index : from 0 Start ( Count from left to right )
Reverse index : from -1 Start ( Count from right to left )

s = 'westos'
print(s[0])
print(s[-2])
# result 
w
o

4、 section

s[start:end:step]
s[:end]:
s[start:]:

Example 1

for x in range(3):
print(f'{
x}',end='')
print()
for x in range(1,4):
print(f'{
x}',end='')
print()
for x in range(1,6,2):
print(f'{
x}',end='')
print()
# result 
012
123
135

Example 2

s = 'westos'
print(s[:5])
print(s[1:3])
# result 
westo
es

summary
Before string n Characters : s[:n]
String except before n Elements other than elements :s[n:]
Copy string :s[:]
Reverse string order :s[::-1]

5、for Loop access

count=0
for item in 'westos':
count +=1
print(f' The first {
count} One letter is {
item}')
# result 
The first 1 One letter is w
The first 2 One letter is e
The first 3 One letter is s
The first 4 One letter is t
The first 5 One letter is o
The first 6 One letter is s

3、 ... and 、 practice

The user enters a string , Judge whether the string is palindrome string
Example aba,abba It's also a palindrome string ,abc It's not a palindrome string

x = str(input(" Please enter the string : "))
if x == x[::-1]:
print(" Palindrome string ")
else:
print(" It's not a palindrome string ")
# result 
Please enter the string : >? aba
Palindrome string

Four 、 String judgment and conversion


1、 Judge data type

s = 'Hello WESTOS'
print(s.isalnum())
print(s.isdigit())
print(s.isupper())
# result 
False
False
False

2、 Conversion of type

print('hello'.upper())
print('HELLO'.lower())
print('HELLO'.capitalize())
# result 
HELLO
hello
Hello

3、 Everyday use of case

choice = input(" Do you want to continue setup (y|Y)")
if choice.lower() == 'y':
print(" Installing program ")
# result 
Do you want to continue setup (y|Y)>? y
Installing program

4、 Determine the beginning and end of the string
Determine the beginning

url = 'http://www.baidu.com'
if url.startswith('http'):
print(f'{
url} yes http agreement ')
# result 
http://www.baidu.com yes http agreement

Determine the ending

filename = input(' Please enter the file type :')
if filename.endswith('.png'):
print(f'{
filename} It's a picture file ')
elif filename.endswith('.mp3'):
print(f'{
filename} It's music files ')
else:
print(f"{
filename} Other documents ")

5、 Data cleaning

lstrip: Remove the space to the left of the string ( It refers to a broad space :\n, \t, '')
rstrip: Delete the space to the right of the string ( It refers to a broad space :\n, \t, '')
replace: Substitution function , Delete the space in the middle ,, Replace the middle space with empty

Example 1
Remove space

" hello ".strip() $ Remove all spaces
'hello'
" hello ".rstrip() $ Remove the space on the right
' hello'
" hello ".lstrip() $ Take out the space on the left
'hello '
" hello hello ".replace(" ","") $ Replace blank space
'hellohello'

Example 2
Adjusting position

print(" Student management system ".center(50))
print(" Student management system ".center(50, "*"))
print(" Student management system ".ljust(50, "*"))
print(" Student management system ".rjust(50, '*'))
# result 
Student management system
********************** Student management system **********************
Student management system ********************************************
******************************************** Student management system

5、 ... and 、 String search and Statistics

1、 Search substring

s = 'hello westos'
print(s.find("to")) $ Spaces also count as a position
print(s.index("to"))
# result 
9
9

summary :
find、 If you find a string , Returns the location of the self created index , Otherwise return -1
idnex, If you find a string , Returns the location of the self created index , Otherwise, the report will be wrong ( Throw an exception )

2、 Separation and splicing of strings
Judge the legitimacy of the address , Each judgment ip Whether in 0 To 255 Between
Use four numbers ’-' Splice up

ip = '172.25.254.100'
item1= ip.split('.') $ Separate
print(f"{
item1}")
item2 = '-'.join(item1) $ Splicing
print(f"{
item2}")
# result 
['172', '25', '254', '100']
172-25-254-100

3、 String practice
# Demand generation 100 A verification code , Each verification code consists of two numbers and 2 Letters

import random
random.choice("0123456789") # Numbers 
import string
string.digits # Numbers 
import string
string.ascii_letters # Case write 

Therefore, the following code can be used to realize

import random
import string
for i in range(100):
print("".join (random.sample(string.digits,2))+"".join (random.sample(string.ascii_letters,2)))
# Realization effect 
50pO
93Zk
30eH
95Xr
92If
...

6、 ... and 、 Exercises


count = 10
right_number = 0
for i in range(10):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*"])
x = eval(f"{
num1} {
symbol} {
num2}") $ python Parse string , Return output
question = f"{
num1} {
symbol} {
num2} = ?"
print(question)
print(type(x), x)
user_answer = int(input(" Your answer is :"))
if user_answer == x:
print(" The answer right ")
right_number +=1
else:
print(" Wrong answer ")
print(" The correct rate is : %.2f%%" %(right_number/count*100)) $ Two %% Indicates transfer %

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved