Example of a string substitution operation in Python

Source: Internet
Author: User
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:

#-*-Coding:utf-8-*-  Import string  values = {' var ': ' foo '}  tem = string. Template ("' Variable: $var Escape: $$ Variable in text: ${var}iable")  print ' TEMPLATE: ', Tem.substitute (value s)  str = "' Variable:% (Var) s Escape: Percent Variable in text:% (Var) siable"  

Output:

TEMPLATE:  variable:foo Escape: $ Variable in text:fooiable  interpolation:  

Regular expression (re) for continuous substitution (replace)
strings are continuously replaced, you can use Replace in succession, or you can use regular expressions.
The regular expression, through the dictionary style, key is to be replaced, value is replaced, a replacement can be.

Code

#-*-coding:utf-8-*-import remy_str = "(condition1) and--condition2--" Print my_str.replace ("Condition1", ""). Replace ( "Condition2", "text") Rep = {"Condition1": "", "Condition2": "text"}rep = Dict ((Re.escape (k), V) for K, V in Rep.iteritems ( ) pattern = Re.compile ("|"). Join (Rep.keys ())) My_str = Pattern.sub (Lambda m:rep[re.escape (m.group (0)), my_str) print My_str

Output:

() and--text--() and--text--
  • Related Article

    Contact Us

    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.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.