SoFunction
Updated on 2024-10-29

Common methods for python strings and simple read and write operations on files

Strings (strings) are the most commonly used data type in Python. We can use quotes (' or ") to create characters.

Characteristics:

-python uses single and double quotes in exactly the same way.
-Use triple quotes (''' or """) to specify a multi-line string.
-Endorser '\'
-Backslashes can be used to escape, using r allows the backslash to be unescaped. E.g. r "this is a line with \n" then \n will be displayed and is not a line break.
-Literally cascading strings such as "this " "is " "string" is automatically converted to this is string.
-Strings can be concatenated together with the + operator and repeated with the * operator.
-Python has two ways of indexing strings, left-to-right starting with 0 and right-to-left starting with -1.
-Strings in Python cannot be changed.
-Python does not have a separate character type; a character is a string of length 1.
-The syntactic format for string interception is as follows: variable [head subscript:tail subscript:step]

python string manipulation common operations, such as string replacement, deletion, interception, assignment, concatenation, comparison, find, split, etc.

String methods return a new value and do not change the value of the original string, whereas dictionaries and lists change the value of the original string.
Define a string

s='a bccc '

1. Remove spaces

result=() # Remove spaces and newlines on both sides of a string by default
print(result)

s1=('c') # If a value is passed, the passed character is removed by default on both sides
print(s1)

print(()) # Remove left space
print(()) # Remove right space

2, the number of statistical keywords

print(('c')) #count the number of keywords

3. Find subscripts

print(('c')) # Find subscripts. An error is reported when it does not exist; when the same character exists, the first position is returned
print(('c')) #look for subscripts。Returns when it does not exist-1

4. Capitalization of letters

print(()) # Initial capitalization
print(()) # Make it all uppercase. For example, the checksum of a CAPTCHA is not case-sensitive
print(()) #All lowercase.

5. Character replacement

print(('4','e')) # Replace the character c with e. When the replaced character does not exist, no error will be reported and no replacement will be made.
print((' ','')) # Remove all spaces and replace them with an empty character
print(('c','fe',1)) #The third parameter indicates how many characters need to be replaced,Replace all if not written

6. Judgment begins or ends with a keyword

print(('.jpg')) # Determine if an image ends in xxx. For example, to upload an image you need to determine if it ends in .jpg
print(''.endswith('.jpg'))

print(('y')) # Determine if it starts with xxx.
print('efg'.startswith('e'))
#True: True; False: False Boolean, used to do the judgment with the

7、Specify the total length, string in the center

print('Welcome on board'.center(50,'*')) #Specify the total length50,Place the characters in the center,If it's not long enough,expense or outlay*make up a deficiency

8, string complement 0

print('1'.zfill(5)) #Auto-completion when the string is not long enough0

9、format、format_map

print(()) #Occupy
print(s.format_map()) # Pass a dictionary

# %s order needs to be one-to-one; format doesn't need to be concerned with order
username='abc'
today='2019-03-30'
s2='wellcome{}make landfall (of typhoon etc),Today's date is{}.'
print((username,today))

s3='insert into user value({username},{password},{phone})'
#format
new_s3=(password='123',username='abc',phone='110')

#format_map
new_s3=s3.format_map({'password':123,
           'username':'ccc',
           'phone':110
           })
print(new_s3)

10, to determine whether the integer

print('123.1'.isdigit()) #Determine if the number is an integer,is returnedtrue,Otherwise, returnfalse

11, to determine whether there are spaces

# Determine whether there are one or more spaces, if it is a space then return True, otherwise return False
print('abc'.isspace()) 
print(' '.isspace())

12. Judgment characters

print('123'.isalnum()) # Judgment returns True as long as there are no special characters, such as numbers or letters; False if there are special characters

print('abc'.isalpha()) Returns True if # is not a number or a special symbol.

13, string split split

users='abc,xiaozi,xiaobai,xiaohei,xiaoming,xiaolan'
users2='abc xiaozi xiaobai xiaohei  xiaoming xiaolan'
# Requirements: the account number and password to become --- 'szz-abc',123456, if it is a string there is no way to deal with it, you need to use the array
# The above strings are comma-separated, so you can split each character by a comma and then take the value

result=(',')
#1. Split by some string;
#2, put the split elements into a list. Return result: ['abc', 'xiaozi', 'xiaobai', 'xiaohei', 'xiaoming', 'xiaolan']

result=('.')
#3, if the specified string does not exist, then put the entire string into the list, return results: ['abc,xiaozi,xiaobai,xiaohei,xiaoming,xiaolan']

result=()
#If split is not specified, it will split by spaces, no matter how many spaces there are in between, return result: ['abc', 'xiaozi', 'xiaobai', 'xiaohei', 'xiaoming', 'xiaolan'].
print(result)

14, the contents of the list into a string

# Convert list to string
names=['abc', 'xiaozi', 'xiaobai', 'xiaohei', 'xiaoming', 'xiaolan']
print(','.join(names))
#1, turn the list into a string
#2、Use the specified string to replace thelistEvery element inside is connected

15. Write the string to the file, pick up 14

# Write strings to files
f=open('','w',encoding='utf-8')
(','.join(names))
()

16. Read the contents of the file

#Read the file; will report an error if the file name does not exist
f=open('','r',encoding='utf-8')
res=()
print('Data read from inside the file:',res)
()

summarize

to this article on the python string common methods and file simple read and write the method of operation of the article is introduced to this, more related python string common methods to read and write the contents of the file, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!