stay Last article in , We learned to be in python in , adopt % as well as format Function to format the string , today , Let's continue to learn a new way :f-string. yes Python3.6 A new string formatting method , It is said that the performance is better than the first two methods , The code also looks more concise .
f-string Use of formatted strings
Simple usage display :
name = 'xiaobo' age = 23 height = 173 print(f"my name is {name},my age is {age}") print(f"my name is {name.upper()},my age is {age+1}") print(f'my height is {height:.2f}') Output is as follows : my name is xiaobo,my age is 23 my name is XIAOBO,my age is 24 my height is 173.00
In addition to some of the usage shown above , There are also some responsible uses , You can expand it yourself when doing formatted output .
Introduction to some common built-in functions of string
name = 'xiaobo' print(len(name))
name = 'my name is xiaobo' print(name.count('m')) # Specify the number of occurrences of a character from a certain position , The specified position coordinates are from 0 Start print(name.count('m', 0)) print(name.count('m', 0, 9)) The output is 2
name = 'abcdmmm' print(name.replace('m', 'n')) print(name.replace('m', 'n', 1)) # You can specify the number of times to replace Output results : abcdnnn abcdnmm
uri = 'username=xiaobo&password=123456&pagesize=20&pagenum=2' print(uri.split('&')) print(uri.split('&',1)) Output is as follows : ['username=xiaobo', 'password=123456', 'pagesize=20', 'pagenum=2'] ['username=xiaobo', 'password=123456&pagesize=20&pagenum=2']
uri = 'username=xiaobo&password=123456&pagesize=20&pagenum=2' print(uri.find('password')) print(uri.find('password', 5, 10)) Output : 16 -1
a = ['a', 'b', 'c'] print(''.join(a)) print('-'.join(a)) Output : abc a-b-c
Some other string checking functions
# Check if the string starts with the specified string print('Hello world'.startswith('He')) # True # Check if the string ends with the specified string print('how are you !'.endswith('!')) # True # Returns a new string , title case , The remaining letters become lowercase print('hEllO, WOrld!'.capitalize()) # Hello, world! # Returns a new string , All words are capitalized , The rest of the letters are in lowercase print('hEllO, WOrld!'.title()) # Hello,World
This article is from WeChat official account. - Xiaobo's road to growth (libotest) , author : Xiaobo knowledge sharing
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .
Original publication time : 2021-09-18
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .