#!/usr/bin/env python #_ *_coding:utf-8 _*_ #replace () method replaces the old string in the string with the new one, and if the third parameter max is specified, the substitution does not exceed Max times. #语法: Str.replace (old, new[, Max]) import Sys,os old_text, new_text, file_name = sys.argv[1], sys.argv[2], sys.argv[3] f = File (file_name, ' rb ') New_file = file ('%s.bak '% file_name, ' WB ') for lin
Python regular expressions are frequently applied to string substitution code in use. A lot of people do not know how to solve this problem, the following code tells you that the problem is extremely simple, I hope you have something to gain.
1. Replace all matched substrings with newstring to replace all substrings in the subject that match the regular expression regex
result, Number = RE.SUBN (regex, new
Python string substitution can be implemented in 2 ways:1 is the method of using the string itself.2 replacing a string with a regularHere's an example to experiment with:A = ' Hello word 'I replaced word in a string with Python1 Replace method with the string itselfA.replace (' word ', ' python ')The result of the output is Hello Python2 use regular expressions
1. Document Progress barCode Requirements:Visualize and increase the number of #的功能.Code implementation:1 #! /user/bin/env Ptyhon2 #-*-coding:utf-8-*-3 #Author:visonwong4 5 ImportSys,time6 forIinchRange (20):7Sys.stdout.write ("#")8 Sys.stdout.flush ()9Time.sleep (0.2)Output Result:1 E:\Python\PythonLearing\venv\Scripts\python.exe e:/python/pythonlearing/ progress bar. PY2 ####################There will b
; a ' Emma ' #\1 represents the first grouped value as sherry, Because there are two sherry, so using \1 can refer to the second one, so that the entire string is replaced by EmmaExample 4:>>> a = Re.sub (' (\d{4})-(\d{2})-(\d{2}) ', R ' \2-\3-\1 ', ' 2018-06-07 ') >>> a ' 06-07-2018 ' >>> a = Re.sub (' (\d{4})-(\d{2})-(\d{2}) ', R ' \gExample 5:Import redef replace_num (str): numdict = {' 0 ': ' 0 ', ' 1 ': ' One ', ' 2 ': ' Two ', ' 3 ': ' Three ', ' 4 ': ' Four ', ' 5 ': ' Five ', ' 6 ': ' S
-third-digit charactersPrintstr[:]#truncate all characters of a stringPrintStr[6:]#Intercept the seventh character to the end of thePrintSTR[:-3]#intercept from the beginning to the third of the last characterPrintSTR[2]#interception of the third characterPrintSTR[-1]#Intercept the first character of the countdownPrintSTR[::-1]#create a string opposite to the original string orderPrintSTR[-3:-1]#intercept the characters before the third and last digitPrintStr[-3:]#intercept the third to the end
#字符串替换Import Sysf = open ("Yesterday2", "R", encoding= "Utf-8")f_new = open ("Yesterday2.bak", "W", encoding= "Utf-8")FIND_STR = sys.argv[1]REPLACE_STR = sys.argv[2]For line in F: If FIND_STR in line: line = Line.replace (FIND_STR,REPLACE_STR) F_new.write (line)F.close ()F_new.close ()#with执行问了, the file is automatically closed! Development specification a line of code cannot exceed 80 characters: \With open ("Yesterday2", "R", encoding= "Utf-8") as F, \ Open ("Yesterday2",
This article mainly introduces the Python basic _ file operation to achieve full-text or single-line replacement method, has a certain reference value, now share to everyone, the need for friends can refer to
When Python modifies a file, using W mode empties/overwrites the original file. You can open it in Read (R) First, write it into memory, and then open it in write (w) mode.
1. The taste in the replace
String substitution (interpolation), you can use string. Template, you can also use the concatenation of standard strings.
String. The template identifies the substituted character, uses the "$" symbol, or uses "${}" within the string; Use the String.substitute (dict) function when calling.
The standard string concatenation, using the "% () s" symbol, is called when the String%dict method is used.
Both can be substituted for characters.
Code:
#-*-Cod
When Python modifies a file, using W mode empties/overwrites the original file. You can open it in Read (R) First, write it into memory, and then open it in write (w) mode.
The taste in the replacement text is tasting
Yesterday when I am young yesterday when I was a teenager the taste of life is sweet the taste of living is sweeter as rain upon my tongue
#将文件读取到内存中with open ("./fileread.txt", "R", encoding= "Utf-8") as F:lines = F.readline
In the original file for partial content substitution, mainly use the Seek () function and truncate () function implementation, directly on the code:# coding:utf-8 import re Path = ' c:/users/lenovo\desktop/20180514152829/cache/576996ede1ef5126fe97d0c4/0.txt ' f1 = open (path ' r+ ' ) Infos = F1.read () Line_new = re.sub (r " " infos) F1.seek (0 ) # the pointer position to the beginning of the file (note: You must do this, otherwi
is a list or tuple, then the _get_value is calledreturn dic#替换参数子方法#数据类型判断, call the unused method after traversaldef replace_target (Self,key, Val, changedata):For Val_ in Val:If Isinstance (Val_, dict):Self.replace_target_value (Key, Val_, Changedata) # The value of the incoming data is a dictionary, then the replace_target_value is calledElif isinstance (Val_, (list, tuple)):Self.replace_target (Key, Val_, Changedata) # The value of the incoming data is a list or a tuple, it calls itselfif _
)Show only letters and numbersdef onlycharnum (s,oth= "): S2 = S.lower (); Fomart = ' abcdefghijklmnopqrstuvwxyz0123456789 ' for C in S2:if not C in fomart:s = S.replace (c, ' ');return s; Print (Onlystr ("a000 aa-b"))Intercept stringstr = ' 0123456789′print Str[0:3] #截取第一位到第三位的字符print str[:] #截取字符串的全部字符print str[6:] #截取第七个字符到结尾print str[:-3] # Intercept from the beginning to the third character before print str[2] #截取第三个字符print str[-1] #截取倒数第一个字符print str[::-1] #创造一个与原字符串顺序相反的字符串print str[-3:-1
Question 1th string substitutionPush the letters in the string backwards by two, for example A to C,z to B and the other characters unchanged.1 defconvert_string (astring):2bstring =' '3 forIinchastring:4 ifOrd'a') 'W')orOrd'A') 'W'):5k = Chr (ord (i) +2)6 elifi = ='y' ori = ='Z':7k = Chr (Ord ('a') +1+ord (i)-ord ('Z'))8 elifi = ='Y' ori = ='Z':9k = Chr (Ord ('A') +1+ord (i)-ord ('Z'))Ten Else: OneK =I ABstring + =k - returnBstrin
, such as>>>a=24>>>a= "Hello World"when we assign a new value to a, the object is not recycled as we say, it will probably still be saved in a system table for the next reference, and one more example:>>>a=45>>>b=45>>>a is bTrueat this point , A and B point to the same object .>>>a=[' A ', ' B ']>>>b=[' A ', ' B ']>>>a is bFalseat this point, a,b points to a different objectWe can use the is operator to verify thatthe is operator is used to check the identity of the object, and returns True if t
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.