String Replacement Operation example in Python, python example

Source: Internet
Author: User

String Replacement Operation example in Python, python example

String replacement (interpolation). You can use string. Template or standard string concatenation.
String. Template indicates the character to be replaced. Use the "$" symbol, or use "$ {}" in the string. Use the string. substitute (dict) function for calling.
Concatenate standard strings and use the "% () s" symbol. When calling, use the string % dict method.
Both can replace 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(values)  str = ''''' Variable : %(var)s Escape : %% Variable in text : %(var)siable '''  print 'INTERPOLATION:', str%values 

Output:

TEMPLATE:  Variable : foo Escape : $ Variable in text : fooiable  INTERPOLATION:  Variable : foo Escape : % Variable in text : fooiable 

Replace regular expression (re)
String replacement. You can use replace or regular expression consecutively.
Regular Expression. The key is to be replaced by the dictionary style, and the value is to be replaced by a regular expression.

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--

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.