Files and Strings(Chapter 10 of Python 3 Object Oriented Programming)
string
1 >>> template = "Hello {}, you are currently {}."
2 >>> print(template.format('Ray', 'writing'))
3 Hello Ray, you are currently writing.
4 >>> template = "Hello {0}, you are {1}. Your name is {0}."
5 >>> print(template.format('Ray', 'writing'))
6 Hello Ray, you are writing. Your name is Ray.
7 >>> template = """
8 public class {0} {{
9 public static void main(String[] args) {{
10 System.out.println({1});
11 }}
12 }}"""
13 >>> print(template.format("MyClass", "print('hello world')"))
14
15 public class MyClass {
16 public static void main(String[] args) {
17 System.out.println(print('hello world'));
18 }
19 }
20 >>> template = """
21 From: <{from_email}>
22 To: <{to_email}>
23 Subject: {subject}
24 {message}"""
25 >>> print(template.format(from_email="a@a.com", to_email="b@b.com", message="message", subject="You got a new message"))
26
27 From: <a@a.com>
28 To: <b@b.com>
29 Subject: You got a new message
30 message
31 >>> print("{} {label} {}".format("x", "y", label="z"))
32 x z y
2 >>> print(template.format('Ray', 'writing'))
3 Hello Ray, you are currently writing.
4 >>> template = "Hello {0}, you are {1}. Your name is {0}."
5 >>> print(template.format('Ray', 'writing'))
6 Hello Ray, you are writing. Your name is Ray.
7 >>> template = """
8 public class {0} {{
9 public static void main(String[] args) {{
10 System.out.println({1});
11 }}
12 }}"""
13 >>> print(template.format("MyClass", "print('hello world')"))
14
15 public class MyClass {
16 public static void main(String[] args) {
17 System.out.println(print('hello world'));
18 }
19 }
20 >>> template = """
21 From: <{from_email}>
22 To: <{to_email}>
23 Subject: {subject}
24 {message}"""
25 >>> print(template.format(from_email="a@a.com", to_email="b@b.com", message="message", subject="You got a new message"))
26
27 From: <a@a.com>
28 To: <b@b.com>
29 Subject: You got a new message
30 message
31 >>> print("{} {label} {}".format("x", "y", label="z"))
32 x z y