Python learning notes (7) Python string (1), learning notes python
String
A String is a String of digits, letters, and underscores. It is enclosed by double quotation marks or single quotation marks.
1 >>> "hello world"2 'hello world'3 >>> 'hello world'4 'hello world'5 >>> "250"6 '250'7 >>> type("200")8 <type 'str'>
The following example:
The first line of a syntax error contains three single quotes. The Python parser cannot match the pair of quotes, so an error is returned.
Solution: 1. Double quotation marks can be used. 2. backslashes and escape characters can be used.
1 >>> 'What's your name?' 2 File "<stdin>", line 1 3 'What's your name?' 4 ^ 5 SyntaxError: invalid syntax 6 >>> "What's your name?" 7 "What's your name?" 8 >>> 'What\'s your name?' 9 "What's your name?"10 >>>
Conversion of strings and numbers
Built-in function int () str () float ()
1 >>> a = int("200") 2 >>> a 3 200 4 >>> type(a) 5 <type 'int'> 6 >>> b = str(200) 7 >>> type(b) 8 <type 'str'> 9 >>> c = float("200.5")10 >>> type(c)11 <type 'float'>12 >>>
Escape Character
Line feed \ n appears in line 3
Solution: Use the backslash \ or + r before the original string to display the original string.
1 >>> print "c:\\news"2 c:\news3 >>> print r"c:\news"4 c:\news5 >>> print "c:\news"6 c:7 ews
String Addition
Concatenates two strings.
1 >>> "3" + "6" 2 '36' 3 >>> "py" + "thon" 4 'python' 5 >>> 8 + "6" 6 traceback (most recent call last): 7 File "<stdin>", line 1, in <module> 8 TypeError: unsupported operand type (s) for +: 'int' and 'str' do not support the addition of int and string. We can convert it to 9> 8 + int ("6 ") 10 1411 >>> str ("8") + "6" 12 '86'