04Python Syntax - Basic Data Type - String

String Assignment

Single quotation mark assignment

a = 'this is a string'
print(a) # this is a string```

Double Quote Assignment

a = "this is a string"
print(a) # this is a string

Assignment of a three-quote string to a variable (multiple lines)

Retains the newline format of the string

# Triple Form
a = '''this is 
a string'''
print(a)
# this is 
# a string

#Triple-Double Form
a = """this is 
a string"""
print(a)
# this is 
# a string

Intercept string or substring

String interception can be obtained from an index like a list, starting with 0

Intercept characters at specified locations (indexes)

a = "this is a string"
print(a[0]) # Intercept the 0th "t" of string a

Gets all the characters after the specified position (index)

a = "this is a string"
print(a[1:]) # Gets all the characters "his is a string" after the string a index is 1 and 1

Intercept all characters before the specified position (index)

a = "this is a string"
print(a[:2]) # Gets the string a index of 2 but does not contain all the characters "th" before 2

Get all characters

a = "this is a string"
print(a[:]) # Getting all the characters of string a is equivalent to print(a)

Gets the characters in a specified location (index interval)

a = "this is a string"
print(a[1:3]) # Gets all the characters "hi" in the string a index from 1 to 3, where the interval is closed and open

Gets a single character in reverse position (index)

String index starts from 0 left-to-right and -1 right-to-left

a = "this is a string"
print(a[-1]) # Gets the string "g" with an index of -1 for string a

Get all the characters before the reverse position (index)

a = "this is a string"
print(a[:-1]) # Gets the character "this is a strin" under all other indexes except the string a index of -1

Gets all the characters in the reverse position (index interval)

a = "this is a string"
print(a[-3:-1]) # Gets all the characters in the string a index from -3 to -2, following the open interval principle of "in" before and after the reverse

Basic use of strings (commonly labeled with *)

*strip()

Remove white space characters at the beginning and end

a = " this is a string "
print(a.strip())
#The result is that the space before and after "this is a string" is removed

lstrip()

Delete blank characters at the beginning (left) (can be remembered as left + strip => lstrip)

a = " this is a string "
print(a.lstrip())
#The result is that the spaces at the beginning (left side of the string) of "this is a string" are removed

rstrip()

Delete blank characters at the end (right) (can be remembered as right + strip => rstrip)

a = " this is a string "
print(a.rstrip())
#The result is that the space at the end of "this is a string" (to the right of the string) is removed

lower()

String to lowercase

a = "This is a String"
print(a.lower())
#The result is that the "this is a string" string is all lowercase

upper()

String to Uppercase

a = "This is a String"
print(a.upper())
#The result is that "THIS IS A STRING" strings are all capitalized

capitalize()

Convert the first character of a string to uppercase

a = "this is a string"
print(a.capitalize())
#The result is "This is a string"

title()

Converts the first letter of each word of a string to uppercase

a = "this is a string"
print(a.title())
#The result is "This Is A String"

*index()

  1. index(str): Gets the index of the first occurrence of a specified character within a string
  2. index(str,start,end): Gets the index of the first occurrence of a specified character within a specified index interval within a string
a = "this is a string"
print(a.index("h"))
#Result is 1,'H'has only one in string a and index is 1

print(a.index("i"))
#The result is 2,'i'has three in string a, but the index() method returns the first index to appear

print(a.index("k"))
#When using the index() method to find a character that does not exist in the original string, the method will fail

print(a.index("i",0,6))
#The result is 2,'i'has two indexes in the index interval [0,6] of a, but the index() method returns the last index that appears for the first time in the specified interval

*rindex()

The index method operates similarly, but returns the index of the last matching string

a = "this is a string"
print(a.rindex("i"))
#The result is 13,'i'has three in string a, and the last index is 13

print(a.rindex("i",0,6))
#The result is 5,'i'has two in the [0,6] interval of string a, and the last index in the specified interval is 5

print(a.rindex("k"))
#When using the rindex() method to find a character that does not exist in the original string, the method will error

*find()

The find and index methods are basically the same.
The only difference is that index does not find an error

a = "this is a string"
print(a.find("h"))
#Result is 1,'H'has only one in string a and index is 1

print(a.find("i"))
#The result is 2,'i'has three in string a, but the find() method returns the index that first appears

print(a.find("k"))
#When using the find() method to find a character that does not exist in the original string, the method does not error and the return value is -1

print(a.find("i",0,6))
#The result is 2,'i'has two indexes in the index interval [0,6] of a, but the find() method returns the last index that appears for the first time in the specified interval

*rfind()

The last occurrence of the returned string, or -1 if there is no match

a = "this is a string"
print(a.rfind("i"))
#The result is 13,'i'has only three in string a, and the last index is 13

print(a.rfind("k"))
#When using the rfind() method to find a character that does not exist in the original string, the method does not error and returns a value of -1

print(a.rfind("i",0,6))
#The result is 5,'i'has two indexes within the index interval [0,6] of a, but the rfind() method returns the last index that appears within the specified interval

*split()

Returns the list type by splitting the string according to the specified separator

a = "this is a string"
print(a.split(" "))
#Split string a into spaces, resulting in ['this','is','a','string']

print(a.split("k"))
# If the split string does not exist in the original string, only one element in the list returned by the group is a
# The result is ['this is a string']

*replace()

Replaces all characters in a string with the specified character

a = 'this is a string'
print(a.replace("i","k"))
#The result is "thks ks a strkng"

print(a.replace("k","f"))
# When the character you want to replace does not exist in the original string, the original string does not change
# The result is this is a string

*count()

Calculates the number of occurrences of a specified string in a string

a = 'this is a string'
print(a.count("i"))
# The result is that 3 "i" occurs three times in a

print(a.count("k"))
# When the specified character does not exist in the original string, 0 returns

center()

Use the specified character (default space) to center and align.
center(num,str):
num is the total length of the aligned character
str is the specified alignment character

a = 'china'
a1 = a.center(50)
#The result is: china                       

a2 = a.center(50,'*')
#The results are: **********************************china*************************

*endswith()

Returns true if the string ends with the specified character and false by default

a = "this is a string"
print(a.endswith("g"))
# The result is True

print(a.endswith("ing"))
# The result is True

print(a.endswith("a"))
# The result is False

print(a.endswith("k"))
# The result is False

*startswith()

Determines whether a string begins with the specified character, returns True, and returns False by default

a = "this is a string"
print(a.endswith("t"))
# The result is True

print(a.endswith("th"))
# The result is True

print(a.endswith("a"))
# The result is False

print(a.endswith("k"))
# The result is False

*isalnum()

Determines whether all characters in a string are alphanumeric, returns True, and returns False by default

a = "this is a string"
print(a.isalnum())
# The result is True

a = "this is a string123"
print(a.isalnum())
# The result is True

a = "this - is a string"
print(a.isalnum())
# The result is False

*isalpha()

The judgement character cannot be empty, and all characters are letters, yes returns True, and default returns False

a = "this is a string"
print(a.isalpha())
# The result is True

a = "this is a string123"
print(a.isalpha())
# The result is False

*isdigit()

Determines whether a string contains only numbers, returns True if it is, or False if it is not

a = "123456"
print(a.isdigit())
#The result is True

a = "123 456"
# The result is that False contains spaces

*isnumeric()

Determines whether a string contains only numeric characters, returns True, otherwise returns False

a = "123"
print(a.isnumeric())
# The result is True

a = "1.23"
print(a.isnumeric())
# The result is a False with the character'.. (Point)

istitle()

Determines whether the string is in title format, returns True, otherwise returns False
(Whether the first character of a word is capitalized)

a = "This Is A String"
print(a.istitle())
# The result is True

a = "this Is A String"
print(a.istitle())
# The result is False

*islower()

Determines whether all lowercase cases are True or False

a = "this is a string"
print(a.islower())
# The result is True

a = "this Is A String"
print(a.islower())
# The result is False

isupper()

Returns True if the string is all uppercase or False if it is not

a = "THIS IS A STRING"
print(a.islower())
# The result is True

a = "this Is A String"
print(a.islower())
# The result is False

isspace()

Returns True if the string contains only spaces, or False if it does not.

a = "   "
print(a.isspace())
# The result is True

a = "1 2 "
print(a.isspace())
# The result is False

a = ""
print(a.isspace())
# The result is False

*len(str)

Get the length of the string

a = "this is a string"
print(len(a))
# The result is 16

*join()

Combines an ordered list of characters specified into a new string

a = ["this","is","a","string"]
print(" ".join(a))
#The result is "this is a string"

print("#".join(a))
#The result is "this#is#a#string"

max()

Gets the largest letter in a string

a = 'abcdfefdga'
print(max(a))
# The result is "g"

min()

Gets the smallest letter in a string

a = 'abcdfefdga'
print(min(a))
# The result is "a"

zfill()

Returns a string of the specified length to the right, preceded by 0

a = "1"
print(a.zfill(3))
#The result is "001"

*format()

String Formatting

output

a = "178.5"
print("My height is {0}cm".format(a))
# The result is "My height is 178.5cm"

'{:.2f}'.format()

Keep two decimal places

a = 178.5
print("My height is %scm" % '{:.2f}'.format(a))
#The result is My height is 178.50cm

'{:+.2f}'.format()

Keep two decimal places signed

a = -178.5
print("length is %s" % '{:+.2f}'.format(a))
#The result is length is -178.50

'{:.0f}'.format()

Do not keep decimals

a = 178.5
print("My height is %scm" % '{:.0f}'.format(a))
#The result is My height is 178cm

'{:x>5d}'.format()

Left padding, 5 for total length after padding, 0 for padding characters, support customization

a =  '{:0>5d}'.format(123)
print(a)
#The result is "00123"

'{:x<5d}'.format()

Right padding, 5 for total length after padding, 0 for padding character, support customization

a =  '{:0<5d}'.format(123)
print(a)
#The result is "12300"

'{:,}'.format()

Comma as separator, often used in thousands of quantities

a = '{:,}'.format(123456789)
print(a)
#The result is "123,456,789"

'{:.2%}'.format()

Percentage format

a = 0.123
print('{:.2%}'.format(a))
# The result is "12.30%"

a = 0.12345
print('{:.2%}'.format(a))
# The result is "12.35%" rounded

a = 0.12345
print('{:.3%}'.format(a))
# The result is "12.345%" 

'{:>10d}'.format()

Right-aligned.10 is the total length after alignment

a = '{:>10d}'.format(12)
print(a)
# The result is "12"

'{:<10d}'.format()

Left-aligned.10 is the total length after alignment

a = '{:<10d}'.format(12)
print(a)
# The result is "12"

'{:^10d}'.format()

Center alignment.10 is the total length after alignment

a = '{:^10d}'.format(12)
print(a)
# The result is "12"

String traversal

Use a for loop to iterate through each character in a string

a = 'this is a string'
for s in a:
	print(s)

#The results are:
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g

Keywords: Python py

Added by gabrielserban on Sun, 20 Feb 2022 19:53:44 +0200