Strings are the most commonly used data types in Python. We can use quotation marks ('or") to create strings.
Creating a string is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!' Var2 = "Python Welookups"
Value in Python access string
Python does not support single-character types, and single characters are also used as a string in Python.
Python accesses substrings, and you can use square brackets to intercept strings, as in the following example:
Instance (Python 2.0+)
The above example execution results:
var1: H var2[1:5]: ytho
Python string update
You can modify an existing string and assign it to another variable, as in the following example:
Instance (Python 2.0+)
The above example execution results
Update String :- Hello Welookups !
Python escape character
Python uses a backslash (\) escape character when you need to use special characters in characters. As shown below:
|\(at the end of the line)||Continuous character|
|\oyy||octal number, the character represented by yy, for example: \o12 stands for line break|
|\xyy||hexadecimal number, the character represented by yy, for example: \x0a stands for line break|
|\other||Other characters are output in normal format|
Python string operator
The following example variable a value is the string "Hello" and the b variable value is "Python":
>>>a + b 'HelloPython'< /div>
|*||Repeat output string||
>>>a * 2 'HelloHello'
|||Get the characters in a string by index||
|[ : ]||Intercept a part of a string||
|in||Member operator - if the string contains the given character returned True||
>>>"H" in a True
|not in||Member operator - if the string does not contain the given character returned True||
>>>"M" not in a True
|r/R||Original String - Original String: All strings are used literally, without special characters that can be escaped or not printed. The original string has almost the same syntax as a normal string except that it is preceded by the letter "r" (which can be capitalized) before the first quote of the string.||
>>>print r'\n' \n >>> print R'\n' \n
|%||Format string||Please see the next chapter|
The above program execution result is：
a + b Output result： HelloPython a * 2 Output result： HelloHello a Output result： e a[1:4] Output result： ell H In the variable a in M In the variable a in \n \n
Python string formatting
Python supports the output of formatted strings. Although this may use very complex expressions, the most basic use is to insert a value into a string with the string formatter %s.
In Python, string formatting uses the same syntax as the sprintf function in C.
#!/usr/bin/python print "My name is %s and weight is %d kg! " % ('Zara', 21)
The output of the above example:
My name is Span> Zara and Span> weight is 21 kg!