Python string operations
How does Python determine that a string contains only numeric characters?
Python string comparison
The following lists the common string operations implemented by python.
1. Copy the string
#strcpy(sStr1,sStr2)sStr1 = 'strcpy'sStr2 = sStr1sStr1 = 'strcpy2'print sStr2
2. connection string
#strcat(sStr1,sStr2)sStr1 = 'strcat'sStr2 = 'append'sStr1 += sStr2print sStr1
3. Search for characters
#strchr(sStr1,sStr2)sStr1 = 'strchr'sStr2 = 'r'nPos = sStr1.index(sStr2)print nPos
4. compare strings
#strcmp(sStr1,sStr2)sStr1 = 'strchr'sStr2 = 'strch'print cmp(sStr1,sStr2)
5. Check whether the scan string contains the specified characters.
#strspn(sStr1,sStr2)sStr1 = '12345678'sStr2 = '456'#sStr1 and chars both in sStr1 and sStr2print len(sStr1 and sStr2)
6. String Length
#strlen(sStr1)sStr1 = 'strlen'print len(sStr1)
7. Convert lowercase characters in the string to uppercase characters
#strlwr(sStr1)sStr1 = 'JCstrlwr'sStr1 = sStr1.upper()print sStr1
8. append a string of the specified length
#strncat(sStr1,sStr2,n)sStr1 = '12345'sStr2 = 'abcdef'n = 3sStr1 += sStr2[0:n]print sStr1
9. String Length comparison
#strncmp(sStr1,sStr2,n)sStr1 = '12345'sStr2 = '123bc'n = 3print cmp(sStr1[0:n],sStr2[0:n])
10. Copy characters of the specified length
#strncpy(sStr1,sStr2,n)sStr1 = ''sStr2 = '12345'n = 3sStr1 = sStr2[0:n]print sStr1
11. String comparison, case insensitive
#stricmp(sStr1,sStr2)sStr1 = 'abcefg'sStr2 = 'ABCEFG'print cmp(sStr1.upper(),sStr2.upper())
12. Replace the first n characters of the string with the specified characters.
#strnset(sStr1,ch,n)sStr1 = '12345'ch = 'r'n = 3sStr1 = n * ch + sStr1[3:]print sStr1
13. Scan strings
#strpbrk(sStr1,sStr2)sStr1 = 'cekjgdklab'sStr2 = 'gka'nPos = -1for c in sStr1: if c in sStr2: nPos = sStr1.index(c) breakprint nPos
14. Flip string
#strrev(sStr1)sStr1 = 'abcdefg'sStr1 = sStr1[::-1]print sStr1
15. Search for strings
Python strstr
#strstr(sStr1,sStr2)sStr1 = 'abcdefg'sStr2 = 'cde'print sStr1.find(sStr2)
16. Split the string
#strtok(sStr1,sStr2)sStr1 = 'ab,cde,fgh,ijk'sStr2 = ','sStr1 = sStr1[sStr1.find(sStr2) + 1:]print sStr1