String correlation function

Posted by richza on Mon, 07 Mar 2022 02:40:24 +0100

String correlation functions and methods

Correlation functions: len, str, eval

1. Str (data) - convert the specified data into a string (when converting, put quotation marks directly outside the printed value of the data)

str(100)   #'100'
str(True)  #'True'

list1 = [10,20,30]
str(list1)     #'[10, 20, 30]'

2. Eval (string) - evaluates the result of a string expression

'[10, 20, 30]' -> [10, 20, 30]

str1 = '[10, 20, 30]'
result = eval(str1)
print(result)         #[10, 20, 30]

correlation method

1. String join()

character string. Join - concatenates the elements in the sequence into a string using the specified string (the elements in the sequence must be strings)


Exercise 1: all the elements in list1 are # connected into a string

list1 = [100, 12.8, True, 'abc']
result = '#'.join(str(x) for x in list1)
list2 = []
for i in list1:
list1 = '#'.join(list2)

Exercise 2: use # to connect all the numeric data in list 1 into a string

list1 = [100, 12.8, True, 'abc',4]
result = '#'.join([str(x) for x in list1 if type(x) in (int,float)])
list2 = []
for i in list1:
    if type(i) == int or type(i) == float:
list1 = '#'.join(list2)


#String 1 Split (string 2) - use all string 2 in string 1 as the cutting point to cut the string

#String 1 Split (string 2, N) - cut the first N string 2 in string 1 as the cutting point

#String 1 Rsplit (string 2, N) - cut the last N string 2 in string 1 as the cutting point

str1 = '123*abc*mn'
result = str1.split('*')
print(result)     #['123','abc','mn'] 

#Note 1: if the cutting point is at the beginning or end of the string, an empty string will appear after cutting

#Note 2: if the cutting points appear continuously, empty strings will also appear after cutting

str1 = '*123*abc*mn*'   #['','123','abc','mn','']
reslut = str1.rsplit('*',2)

3.replace - replace

#String 1 Replace (string 2, string 3) - replaces all string 2 in string 1 with string 3

#String 1 Replace (string 2, string 3, N) - replaces the first N string 2 in string 1 with string 3

str1 = 'how are you? i am fine, thank you! and you?'
result1 = str1.replace('you','me')

result2 = str1.replace('you','me',2)

#Exercise: replace the last two you in str1 with me

result = 'me'.join(str.rsplit('you',2))

4. Replace characters

#Str.maketrans (string 1, string 2) - create a one-to-one correspondence table between all characters in string 1 and all characters in string 2

#String Translate (character mapping table) - replace the characters in the string according to the relationship of the character correspondence table

str = '1234567'
table = str.maketrans('1234567','One, two, three, four, five, six days')

5. Delete the blanks at both ends of the string

#String strip() - delete the blanks on both sides of the string

#String rstrip() - delete the blank space to the right of the string

#String lstrip() - delete the blank space on the left of the string

str = 'name//'

6.count - count

String 1 Count (string 2) - counts the number of occurrences of string 2 in string 1

str1 = 'how are you? i am fine, thank you! and you?'


character string. center(N, character), string rjust(N, character), string ljust(N, character)


isdigit, isnumeric - judge whether it is a pure digital string

#isdigit - numeric characters: '0' - '9'‘

#isnumeric - numeric character: the meaning of a character is a character representing a numeric value

Format string

1. String formatting

name = input('Please enter your name:')
age = int(input('Please enter age:'))

#xxx is xx years old this year

Scheme 1: String splicing

message = name + 'this year' + str(age) + 'Years old!'

Scheme 2: format string


1) Format string: string containing format placeholder% (data 1, data 2, data 3,...)

Note: the number of data in () must correspond to the placeholder in the string one by one

2) Format placeholder

%s - string placeholder, which can correspond to any type of data

%d - integer placeholder, which can correspond to any number

%f - floating point placeholder, which can correspond to any number

%. Nf - floating point placeholder, which can correspond to any number and keep the decimal to N decimal places

Suggestion: how to control the number of decimal places? You can use% s to occupy all decimal places


money = 18000
gender = 'male'
#xxx, gender: x, age: xx, monthly salary: XXXXX 00 yuan!
#'% s, gender:% d, age:% d, monthly salary:% f Yuan'% (name, gender,age,money)

message = '%s,Gender:%s,Age:%d,a monthly salary:%.2f element' % (name, gender,age,money)

Scheme 3: f-string

1) Basic usage

#Syntax f '{expression}' - splice the value of the expression in {} into a string as string content

message = f'{name},Gender:{gender},Age:{age},a monthly salary:{money}element'

#2) Add parameter

f '{provide data expression: parameter}‘

a. Parameters controlling decimal places

f '{expression:. Nf}' - keep N decimal places

b. Amount value display plus comma

Comma only: f '{expression:}'

money = 1800000
result = f'amount of money:{money:,}element'

Add a comma and control the number of decimal places

result = f'amount of money:{money:,.2f}element'

c. Display percentage: f '{expression:. N%}' - controls the decimal places of the percentage

x = 0.34
result = f'growth rate:{x:.2%}'

d. Control length

F '{expression: character > n}', f '{expression: character > n}'

x = 'abc'

result = f 'Name: {x}'

Topics: Python Algorithm leetcode