Location>code7788 >text

Getting started with strings

Popularity:380 ℃/2025-03-07 18:29:40

String function -index-find

#1. Define string.
s1 = "hello and python and java and sql and scala"


#2. Demonstrate the above functions.
print(('and'))                               #6. Because a string consists of multiple characters, the index of the first character of the string will be returned by default.
print(('and', 7, 30))      # 17
print(('and', 7, 19))      #-1, the left and right packages are not included, the index cannot be retrieved 19
print('-' * 28)

print(('and'))                               #6. Because a string consists of multiple characters, the index of the first character of the string will be returned by default.
print(('and', 7, 30))      # 17
#print(('and', 7, 19)) # Report an error
print('-' * 28)


#Demonstrate the effects of rfind() and rindex() are the same, the difference is whether an error is reported when it cannot be found.
print(('and'))      # 34
print(('and', 10, 30))      # 26
print(('and', 10, 19))      # -1
print('-' * 28)

print(('and'))      # 34
print(('and', 10, 30))      # 26
#print(('and', 10, 19)) # If not found, an error will be reported

String function-replace-split

#1. Define the string variable s1 and record the data to be operated.
s1 = 'hello and python and sql and linux'


#2. Demonstrate the replace() function.
s2 = ('and', 'or')            #Don't write a number, replace all
s3 = ('and', 'or', 2) #Write a number, write a few to replace several.

#3. Print the result:
print(f's1: {s1}')      #s1 is an immutable type and the content remains unchanged.
print(f's2: {s2}')
print(f's3: {s3}')
print('-' * 28)


#4. Demonstrate the split() function.
list1 = ('and')
print(type(list1))      #<class 'list'> list is also a type of container type.
print(list1)            # ['hello ', ' python ', ' sql ', ' linux']


list2 = ('and', 2)
print(type(list2))      #<class 'list'> list is also a type of container type.
print(list2)            # ['hello ', ' python ', ' sql and linux']
print('-' * 28)


#Extension: len() function, obtains the length of the string, that is: how many characters does the string have.
print(len(s1))          # 34
print('-' * 28)


#Delimiter.join(string) Separates each character in the string with a delimiter.
s4 = 'hello'
s5 = ','.join(s4)
print(s5)       # h,e,l,l,o


#Requirements: Put 'hello' => ['h', 'e', ​​'l', 'l', 'o']
list3 = ','.join(s4).split(',')
print(list3)        # ['h', 'e', 'l', 'l', 'o']