String to get started with Python

Keywords: Python Java shell less

The string to get started with Python

1. The concept and creation of strings

1. The concept of string

*In programs, text content is represented as a string

*Strings are composed of a series of ordered characters, such as:'helloworld'

*Strings and lists, tuples, are of sequence type'

*You can think of strings as lists of characters, and many operations of lists apply to strings as well.

*There is no separate character type, a character is a string containing an element such as:'a','b','c'


2. String Creation

'''
//Strings can be created using double or single quotation marks
'''
s = 'ok'
print (s,type(s)) # ok <class 'str'>

s1 = "ok1"
print (s1,type(s1)) # ok1 <class 'str'>


'''
//With the built-in function str, the input can be a number, a letter, or a floating point number, and the final data type is str
'''

s2 = str('abc')
print (s2,type(s2)) # abc <class 'str'>

s3 = str('123')
print (s3,type(s3)) # 123 <class 'str'>

 

2. Escape Characters

1. Special characters that cannot be represented by escape characters

When a string contains special characters that cannot be directly represented, such as line breaks, carriage returns, horizontal tabs, backspaces, etc., what do you mean?

Line break: newline, cursor moves to the beginning of the next line

Enter: return, cursor moved to the beginning of the line

Horizontal tab: tab key, cursor moves to the start of the next set of four spaces

Backspace: backspace key, one character back

You can use the following escape characters

Line Break:\n

Enter:\r

Horizontal tab: \t

Backspace:\b

print('abc\ndef') #abcdef newline display
print('abc\rdef') #def Enter, move to the beginning of the light sample line
print('123456\t123\t45') #123456 123. 45 Tab 4 spaces, in whole character length
print('abc\bdef') #abdef backspace, deleting c


2. Use backslash'\'as escape character

For example, if you want to print a string directly, but want to include single, double, and so on, you need to escape it with \

print('what\'s you name') # what's you name
print('Print a double quotation mark\"') #Print a double quotation mark
print('Print a backslash\\') #Print a backslash\


3. Original string

For example, if you want to print'\tC:\Program Files'-t as a tab and do not want -t to take effect, you can use the original string raw

print('\t:programfiles')  #	:programfiles
print(r'\t:programfiles') #\t:programfiles
print(R'\t:programfiles') #\t:programfiles


4. String lookup operation

a) Use index, rindex, find, rfind to find the index of elements in a string

s = '12334567'
print(s.index('3')) # 2 
print(s.rindex('3')) # 3
print(s.find('3'))  # 2 
print(s.rfind('3')) # 3
#You can specify to look up start and stop, for example, from index 1 to index 5, to look up the index of element 3
print(s.index('3',1,5)) # 2
print(s.rfind('3',1,5)) # 3
#The index and rindex methods throw a value error when the element found is not in the specified index
#find and rfind methods return -1 when the element being searched is not in the specified index
print(s.index('9',1,5)) # ValueError: substring not found
print(s.rindex('9',1,5)) # ValueError: substring not found
print(s.find('9',1,5))  # -1 
print(s.rfind('9',1,5)) # -1

b) You can also use the lookup list lookup operation to find the elements of the corresponding index

s = 'Python'
print(s[3])  # h
print(s[1:4]) # yth
print(s[:-1]) # Pytho
print(s[::-1]) # nohtyP
print(s[:])  # Python
print(s[:2:-1]) # noh


5. String comparison

a) Use >, <, ==,!= to compare strings

s1 = 'abc'
s2 = 'def'
print(s1 == s2) # False
print(s1[0] < s2[0]) # True
print(s1[1] > s2[0]) # False
print(s1 != s2) # True

b) Strings can also be used with is, == is comparative equality, is comparative identity, but for strings, python makes repeated calls


a = b = '123'
c = '123'
print (a is b) #True
print (a == c) #True
print (a is c) #True
print(id(a),id(c))  #139917133452656 139917133452656


6. String inversion

Reverse strings using the built-in function reversed

s = 'hello world'
print(list(reversed(s)))  # ['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']


7. Sorting strings

Sorting strings using the built-in function sorted

s = 'EdfaCb'
#You can specify a collation, such as converting to lowercase and then sorting, or inverting strings after sorting
#ord() if no rule is specified
print(sorted(s,key = str.lower)) # ['a', 'b', 'C', 'd', 'E', 'f']
print(sorted(s,reverse = True)) # ['f', 'd', 'b', 'a', 'E', 'C']
print(sorted(s)) # ['C', 'E', 'a', 'b', 'd', 'f']


8. Case conversion of strings

a) upper converts all characters to uppercase

b) lower converts all characters to lowercase

c) swapcase converts all lowercase to uppercase, uppercase to lowercase

D) Tile converts the beginning of each word to uppercase

s = 'java PytHon Shell'
print(s.lower()) #java python shell
print(s.upper()) # JAVA PYTHON SHELL
print(s.swapcase()) # JAVA pYThON sHELL
print(s.title()) # Java Python Shell


9. Alignment of strings

a) center Center alignment

b) rjust right alignment

c) ljust left alignment

The above method can specify two parameters, the first is the width, the second is the alignment symbol, and the second parameter is not specified as a space by default.

d) zfill: right aligned, left filled with 0

The method value receives a parameter specifying the width of the character and returns the string itself if the specified character width is less than the string itself

s = 'hello world'
print(s.center(20,'*')) # ****hello world*****
print(s.ljust(18,'^')) # hello world^^^^^^^
print(s.rjust(18,'$')) # $$$$$$$hello world
print(s.zfill(15)) # 0000hello world


10. Replacement of strings

Call the replace method to replace the string, str.replace('old','new','replace_num')

s = 'hi hi hi hello'
#Replace hi with hello, maximum number of replacements is 2, no number of replacements specified defaults to all
print(s.replace('hi','hello',2)) # hello hello hi hello


11. Remove leading and trailing characters from strings

Call methods lstrip, rstrip, strip to remove string leading and trailing characters

s = '****hello world^^^^^'
print(s.lstrip('*'))  # hello world^^^^^
print(s.rstrip('^'))  # ****hello world
print(s.strip('*^'))  # hello world


Posted by jamey on Sun, 05 Jan 2020 22:54:33 -0800