String operation in Python

Keywords: Python

String assignment to variable

str1 = 'hello world'

 

String print view

str1 = 'hello world'
print(str1)

 

String length printing

str1 = 'hello world'
print(len(str1))

Note: the len method returns only one length and does not print

 

Content index position confirmation in string

Method 1

 

str1 = 'hello world'
print(str1.find('x'))           # Returns the index position of the first found keyword. If the specified keyword is not returned in the string-1 Value.

 

Method 2

 

str1 = 'hello world'
print(str1.index('l'))          # Returns the index position of the first key found. If the specified key is not in the string, an error will be reported directly

 

String view by index location

str1 = 'hello world'
print(str1[1])

 

String slice by position view

str1 = 'hello world'
print(str1[0:5])                 # The slice index will not contain the rightmost value

 

String specified location content substitution

str1 = 'hello world'
print(str1.replace('l','L',2))      # The following 2 are default parameters, which can not be added; it means the first two times'l'Key to'L'

 

String case conversion

str1 = 'hello world'
print(str1.upper())         # Convert lowercase to uppercase

str1 = 'HELLO WORLD'
print(str1.lower())         # Convert upper case to lower case

str1 = 'hello world'
print(str1.title())         # Capitalize the first letter of each word in the string content

str1 = 'Hello World'
print(str1.swapcase())      # Case interchangeability

 

String length setting

str1 = 'hello world'
print(str1.center(30,'.'))  # Sets the string length and specifies the fill content; does not specify the default is space

 

Escape of special symbols in string

str1 = 'hello\fworld'
print(str1.expandtabs())        # Declare the meaning of a special escape character in a string
Special escape character
\n Newline character
\t horizontal tab
\v Vertical tab
\f Page changing character
\e Escape character
\ Escape character
\a Bell
\b BS-Backspace
\000 empty

 

 

 

 

 

 

 

 

 

 

 

 

Space removal in string

str1 = '   hello world   '
print(str1.strip())             # Remove space before and after
print(str1.lstrip())            # Remove space after
print(str1.rstrip())            # Remove preceding spaces

 

String to list

str1 = 'develop, operations, test'
list1 = str1.split(',')         # Converts a string to a list and separates the string with the specified separator

Posted by davelr459 on Sat, 30 Nov 2019 03:20:47 -0800