7 days playing Python(4) Python string

Keywords: Python

Formatting of strings

Syntax for string formatting: 's%'% str1

                                         "s%s%"%(str1,str2)

str1 = "version"
num = 1
print("str:%s" % str1)
print("num:%d str1:%s" % (num, str1))

String operation on it

word = "version3.0"
print(word.center(20))               #Output 5 spaces on both sides of variable
print(word.center(20, "*"))          #Output 5 on both sides of variable*
print(word.ljust(0))                 #Output left justified
print(word.rjust(20))                #Output 20 characters with 10 spaces on the left

Escape character to string

word = "\thello world\n"
print("Direct output:", word)
print("strip()", word.strip())     #Remove escape characters
print("lstrip()", word.lstrip())   #Remove left escape character
print("rstrip()", word.rstrip())   #Remove right escape character

String merging

python uses "+" to connect strings. python will decide to perform connection or addition operations according to the types on both sides of "+". If both sides are strings, the join operation will be performed; if both sides are numeric types, the addition operation will be performed; if both sides are different types, an exception will be thrown.

str1 = "hello"
str2 = "python"
result = str1+str2
print(result)

python also provides the join() function for string merging

strs = ['hello',"python"]
print(" ".join(strs))

String truncation

Use index to intercept substring

word = "python"
print(word[4])

Special slice truncation substring

s1 = 'hello python'
print(s1[0:3])
print(s1[::2])
print(s1[1::2])

split() get substring

sentence = "Bob said:1,2,3,4"
print(sentence.split())         #Space truncation substring
print(sentence.split(","))      #Comma truncation substring
print(sentence.split(",", 2))    #Both are good at intercepting substrings

String comparison

In python, use "= =" and "! ="Compares the contents of two strings

str1 = 1
str2 = '1'
if str1 == str2:
    print("Equal")
else:
    print("Unequal")

if str(str1) == str2:
    print("Equal")
else:
    print("Unequal")

startwith() and endwith()

word = "hello world"
print("hello" == word[0:5])
print(word.startswith("hello"))
print(word.endswith("ld",  6))
print(word.endswith("ld",  6,  10))
print(word.endswith("ld",  6,  len(word)))

Inversion of strings

Output strings in reverse order by slicing

print(word[::-1])
for i in range((len(word)), 0, -1):
   print(word[i-1])

Finding and replacing strings

The find() method is used to find the string and return the index of the first occurrence of the character

word1 = "this is a apple"
print(word1.find("a"))
print(word1.rfind("a"))

python uses replace() to replace strings

sentence = "hello world,hello china"
print(sentence.replace("hello", "hi"))
print(sentence.replace("hello", "hi", 1))

 

 

 

 

Posted by nrg_alpha on Sat, 04 Jan 2020 11:10:29 -0800