python Python.DataTypes.Strings

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python.DataTypes.Strings相关的知识,希望对你有一定的参考价值。

CODE = { 'A': '.-',     'B': '-...',   'C': '-.-.', 
        'D': '-..',    'E': '.',      'F': '..-.',
        'G': '--.',    'H': '....',   'I': '..',
        'J': '.---',   'K': '-.-',    'L': '.-..',
        'M': '--',     'N': '-.',     'O': '---',
        'P': '.--.',   'Q': '--.-',   'R': '.-.',
        'S': '...',    'T': '-',      'U': '..-',
        'V': '...-',   'W': '.--',    'X': '-..-',
        'Y': '-.--',   'Z': '--..',
        
        '0': '-----',  '1': '.----',  '2': '..---',
        '3': '...--',  '4': '....-',  '5': '.....',
        '6': '-....',  '7': '--...',  '8': '---..',
        '9': '----.' 
        }


        
        
def dictreverse(mapping):
    """
    Function: dictreverse
    Description: Swaps values and keys of dictionary
    Input: dictionary
    Output: dict with swapped key/values
    Usage : a = dictreverse(c)
    Notes : Returns a new dictionary with keys and values swapped.
        >>> dictreverse({1: 2, 3: 4})
        {2: 1, 4: 3}
    """
    return dict([(value, key) for (key, value) in mapping.items()])
       



def string_morse(string):

    global CODE
    outstring = ''
    
    msg = string
    for char in msg:
        outstring += " " + (CODE[char.upper()])
    
    #print(CODE)
    return outstring[1:]
    
    
def morse_string(mor):
    
    global CODE
    CODEREV = dictreverse(CODE)
    outstring = ''
    
    if mor.contains(" "):
        msg = mor.split(" ")
    
        for char in msg:
            #print(char)
            outstring = outstring + (CODEREV[char.upper()])
    
        return outstring
    else:
        return "Input string not space separated"
    
    
        
def main():
    
    print(string_morse("panagos"))
    print(morse_string(string_morse("panagos")))
    # print(CODE)
    # print("######")
    # print(dictreverse(CODE))
    # print("######")
    
    
    
    # msg = input('MESSAGE: ')
    
    # for char in msg:
        # print (CODE[char.upper()], end = '')
        
if __name__ == "__main__":
    main()
1. string_filter.py         : Filter substring out of string
2. find_index.py            : Find the index of specific element
3. count_occur.py           : Count occurrences of a character in a string
4. remove_punctuation       : Removes all punctuation characters
5. parse_string.py          : Parses all non punctuation elements, stores in list
6. randomize_string.py      : Randomizes a string (anagram)
7. tokenize_string.py       : Tokenizes a string based on delimiter
8. to_octal.py              : Converts a string to octal
9. to_dec.py                : Converts a string to decimal
10.to_hex.py                : Converts a string to hex
11.to_binary.py             : Converts a string to binary and back
11.string_padding.py        : Pads a string with specified digit, up to length
12.iter_string_sub.py       : Iterate over substrings of a string
13.replace_tabs.py          : Replace tab with specified number of spaces
14.count_alpha.py           : Returns longer string in alphabetic order
15.count_alpha_rev.py       : Returns longer string in alphabetic order (reversed)
16.count_string.py          : Returns occurrences of a substring in string
17. count_string_no.py      : Returns occurrences of substring in string(non overlapping)
18. count_vowels.py         : Returns count of vowels in string
19. count_consonants.py     : Returns count of consonants in string
20. count_numbers.py        : Returns count of numbers in a string
21. count_any_string.py     : Returns count of specified characters
22. count_white.py          : Returns count of whitespaces in string
23. count_tab.py            : Returns count of tab in string
24. count_string(Str len)   : Returns total count of string characters
24. stringtotuple           : Converts a string to tuple
25. stringtolist            : Converts a string to list
26. listtostring            : Converts a list into a string
27. tupletostring           : Converts a tuple into a string
28. splitbyn                : Split string into substrings of specified length
28. stringsubset            : Subset strings into gradually increasing digits
29. Validatestring          : Various functions for string validation
30. StringtoMorse           : Converts a string to Morse code and back
def string_removemid(lista, numberstart, numberend):
  '''
  Function: list_removemid
  Description: Removes from the mid of string
  Used as: a = string_removebeg(lista, number)
  Notes: Same as list_removebeg. Does not edit in place.
         Works on list, tuples, strings.
  '''  
  output_list = lista[:numberstart] + lista[numberend+1:]
  return output_list
  
  
  
  
a = 'panagosasdasdasd'
b = [ 1, 2, 3, 4, "x", 5, 3, 2, 7, 6 ]
c = ( 1, 2, 3, 6, 4, 3, 2,)


print (list_removemid(b, 1, 4))
print (list_removemid(a, 1, 3))
print (list_removemid(c, 2, 5))
def string_removeend(lista, number):
  '''
  Function: list_removeend
  Description: Removes from the end of string
  Used as: a = string_removebeg(lista, number)
  Notes: Same as list_removebeg. Does not edit in place.
         Works on list, tuples, strings.
  '''
    lengthof = len(lista)
    calc = lengthof - number
    output_list = lista[:calc]
    return output_list


a = 'panagosasdasdasd'
b = [ 1, 2, 3, 4, "x", 5, 3, 2, 7, 6 ]
c = ( 1, 2, 3, 6, 4, 3, 2,)

#print (list_removeend(a, 1))
#print (list_removeend(b, 2))
#print (list_removeend(c, 1))
def string_removebeg(lista, number):
  '''
  Function: string_removebeg
  Description: Removes from the beginning of string
  Used as: a = string_removebeg(lista, number)
  Notes: Same as list_removebeg. Does not edit in place.
         Works on list, tuples, strings.
  '''
  output_list = lista[number:]
	return output_list
	
	
	
a = 'panagosasdasdasd'
b = [ 1, 2, 3, 4, "x", 5, 3, 2, 7, 6 ]
c = ( 1, 2, 3, 6, 4, 3, 2,)


#print (list_removebeg(a, 2))
#print (list_removebeg(b, 3))
#print (list_removebeg(c, 1))
def checklength(string_in):
    '''
    Function: checklength 
    Description: Checks the length of the script
    Input: string
    Output: Boolean
    Usage: if checklength(string):
    Notes: Simple validation
    '''
    if len(string_in) <> 29:
        return False
    else:
        return True
def tooct(string1):
    '''
    Function : Converts a string to oct
    Called as : tohex(string1)
    Notes : Translates everything including special characters, newlines
    '''
    strout = ''
    for i in string1:
        strout += str(oct(ord(i)))
    return strout
    #print (strout)
def tohex(string1):
    '''
    Function : Converts a string to hex
    Called as : tohex(string1)
    Notes : Translates everything including special characters, newlines
    '''
    strout = ''
    for i in string1:
        strout += str(hex(ord(i)))
    return strout
    #print (strout)
def tobinary(str):
    #to_conv = bytes(str, "ascii")
    #print(' '.join(["{0:b}".format(x) for x in to_conv]))
    b = ''.join(format(ord(x), 'b') for x in str)
    return b
    
    
print (tobinary("panagos"))
print (tobinary("hello world"))


def bintoascii(stri):
    a = ''.join(chr(int(stri[i:i+8], 2)) for i in range(0, len(str(stri)), 8))
    return a
    
print (bintoascii("1101000110010111011001101100110111110000011101111101111111001011011001100100"))



def tobits(s):
    result = []
    string = ''
    for c in s:
        bits = bin(ord(c))[2:]
        bits = '00000000'[len(bits):] + bits
        result.extend([int(b) for b in bits])
    
    for j in result:
        string += str(j)
    return (result, string)

def frombits(bits):
    chars = []
    for b in range(int(len(bits) / 8)):
        byte = bits[b*8:(b+1)*8]
        chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
    return ''.join(chars)
    
    
print (tobits("panagos")[1])
b = tobits("panagos")[1]
print (frombits(b))


def strtotuple(string):
    out = ()
    for s in string:
        out = out + (s,)
    return out
    
    
print (strtotuple(b))
def stringsubsets(string1):
    '''
    Name: String Subsets
    Function: stringsubsets(string)
    Input: string, or string variable
    Output: list
    Usage: a = stringsubsets(string1)
    Notes: Used anywhere, no modules required
    '''
    i = 0
    output = []
    for j in range(1, len(string1) + 1, 1):
        output.append(string1[:j])
    return output
    
print (stringsubsets("panagos"))
def anagram(string):
  '''
  Function: anagram
  Description: Makes an anagram out of a string
  Input: string
  Output: anagrammed string
  Usage: a = anagram(string)
  Notes: Does not edit in place, requires random module
  '''
    import random
    lista = []
    outLista = []
    outstring = ''
    x = 0
    
    # Convert to list
    for i in string:
        lista.append(i)
        
    for i in (range(len(lista))):
        x = random.randint(0,(len(lista)-1))
        outLista.append(lista[x])
        del lista[x]
        
    for i in outLista:
        outstring = outstring + str(i)
        
    return outstring
    
print (anagram('panos'))
##################################

#Composing together this function and the split method from the previous section makes a useful combination — we’ll clean out the punctuation, and split will clean out the newlines and tabs while turning the string into a list of words:
# Needs the remove punctuation function!!!!!!

my_story = """
Pythons are constrictors, which means that they will 'squeeze' the life
out of their prey. They coil themselves around their prey and with
each breath the creature takes the snake will squeeze a little tighter
until they stop breathing completely. Once the heart stops the prey
is swallowed whole. The entire animal is digested in the snake's
stomach except for fur or feathers. What do you think happens to the fur,
feathers, beaks, and eggshells? The 'extra stuff' gets passed out as ---
you guessed it --- snake POOP! """

wds = remove_punctuation(my_story).split()
print(wds)

#The output:

#['Pythons', 'are', 'constrictors', ... , 'it', 'snake', 'POOP']

def parse_string(s):
  '''
  Function: parse_string 
  Description: Parse given string to words, sort in array
  Input: string
  Output: Array of words
  Usage: b = parse_string(s)
  Notes: Will split on single whitespace
  '''
    def remove_punctuation(s):
        punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
        s_sans_punct = ""
        for letter in s:
            if letter not in punctuation:
                s_sans_punct += letter
        return s_sans_punct
        
    temp = remove_punctuation(s).split()
    return temp



    
my_story = """
Pythons are constrictors, which means that they will 'squeeze' the life
out of their prey. They coil themselves around their prey and with
each breath the creature takes
"""

#wds = remove_punctuation(my_story).split()
wds = (parse_string(my_story))
print(wds)
def padstring(str,target,padding, position = 1):
  '''
  Function: padstring
  Description: Pads a string with specified padding up to target
  Input: string, target number (ie 30), padding (ie 'O'), position = 1 or 0
  Output: string with padding to the left or right
  Usage: a = padstring(string, 30, '0', 1)
  Notes: Does not edit string in place
  Notes2: Position(1) = Left padding / Position(2) = Right Padding
  '''
    outstring = ''
    length = len(str)
    if target < length:
        return False
    elif target == length:
        return str
    else:
        # Calc dif
        diffdigit = target - length
        tempstring = (padding)*(int(diffdigit)) 
        if position == 1: 
            outstring = tempstring + str
            return outstring
        else:
            outstring = str + tempstring
            return outstring
        
a = 'abcdsdfsdfd'
print (padright(a, 15, '0', 0))
def listtostr(list):
    out = ''
    for s in list:
        out += str(s)
    return out
def iter_slices(string, slice_length):
    """
    Function: iter_slices
    Description: Iterates over specified substrings of a string
    Input: string, slice_length
    Output: slice_length pieces of string
    Notes: Iterate over slices of a string.
    Usage: See below.
    """
    pos = 0
    while pos < len(string):
        yield string[pos:pos + slice_length]
        pos += slice_length

if __name__ == '__main__':

    s = "abcdefg"
    for i in iter_slices(s, 2):
        print i
    #result:
    #ab
    #cd
    #ef
    #g
def find(strng, ch):
    '''
    Function: find_index
    Description: Find and return the index of ch in strng. Return -1 if ch does not occur in strng.
    Input: string, character
    Output: index of character in string, or -1
    Usage: print (find(str,char))
    '''
    ix = 0
    while ix < len(strng):
        if strng[ix] == ch:
            return ix
        ix += 1
    return -1

test(find("Compsci", "p") == 3)
test(find("Compsci", "C") == 0)
test(find("Compsci", "i") == 6)
test(find("Compsci", "x") == -1)


############33


def find2(strng, ch, start):
    '''
    Function: find2
    Description: Find and return the index of ch in strng. Return -1 if ch does not occur in strng.
    Input: string, character, start digit
    Output: index of character in string, or -1
    Usage: print (find2(str,char))
    Notes: Search after specific index in string (Start)
    '''
    ix = start
    while ix < len(strng):
        if strng[ix] == ch:
            return ix
        ix += 1
    return -1

test(find2("banana", "a", 2) == 3)


##############

def findimpr(strng, ch, start=0):
  '''
    Function: findimpr
    Description: Find and return the index of ch in strng. Return -1 if ch does not occur in strng.
    Input: string, character, start digit
    Output: index of character in string, or -1
    Usage: print (find(str,char))
    Notes: Search after specific index in string (Start)
    Notes: Same as above, but default start equals to zero 
    '''
    ix = start
    while ix < len(strng):
        if strng[ix] == ch:
            return ix
        ix += 1
    return -1
    
###############

def find(strng, ch, start=0, end=None):
    ix = start
    if end is None:
       end = len(strng)
    while ix < end:
        if strng[ix] == ch:
            return ix
        ix += 1
    return -1

# ########################
# Function : countwhite
# Usage : countconso(string)
# Example : print countconso(string)
# Output : Counts the amount of whitespace 
# Note : Pre declared consonants, all. 
# Method : Iterates over letters in string, checks if each letter exists "in" the 
# provided list, and if it does it increments the num_conso.
#
# Define Function
def countwhite(string):
    # initialize variable
    num_numbers=0
    # iterate over string
    for char in string:
        # iterate over list of characters
        if char in " ":
            num_numbers += 1
    return num_numbers

# count = str(countwhite(s))
# print ( "Number of Vowels : " + count )
# ########################
# Function : countvowel
# Usage : countvowel(string)
# Example : print countvowel(string,'bob')
# Output : Counts the amout of vowels 
# Note : Pre declared vowels, all. 
# Method : Uses "asdasd".count(pattern) method. 
#
# Define Function
def countvowel(string):
    # initialize variable
    num_vowels=0
    # iterate over string
    for char in string.lower:
        # iterate over list of characters
        if char in "aeiouyw":
            num_vowels += 1
    return num_vowels

# count = str(countvowel(s))
# print ( "Number of Vowels : " + count )
# ##
#
# ########################
# Function : countwhite
# Usage : countconso(string)
# Example : print countconso(string)
# Output : Counts the amount of whitespace 
# Note : Pre declared consonants, all. 
# Method : Iterates over letters in string, checks if each letter exists "in" the 
# provided list, and if it does it increments the num_conso.
#
# Define Function
def countwhite(string):
    # initialize variable
    num_numbers=0
    # iterate over string
    for char in string:
        # iterate over list of characters
        if char in "\t":
            num_numbers += 1
    return num_numbers

# count = str(countwhite(s))
# print ( "Number of Vowels : " + count )


print ("Count tab is : " + str(countwhite("pana\t\t\t")))
# ########################
# Function : countnonoverlap
# Usage : countnonoverlap(string,pattern,casesensitive=True/False)
# Example : print countnonoverlap(string,'bob')
# Output : Counts the count of occurences of 'pattern' in a string 
# Note : Counts non overlapping occurences 
# Method : Uses "asdasd".count(pattern) method. 
#
# Define Function
def countnonoverlap(string,pattern,casesensitive=True):
	# Check for case sensitivity
    if casesensitive != True:
        string  = string.lower()
        pattern = string.lower()
	# Set the length of the pattern to l
    l = len(pattern)
	# Initialize a counter at zero
    ct = 0

    return string.count(pattern)

# DEBUG
#test = 'my maaather lies over the oceaaan'
#print (test)
#print (countnonoverlap(test,'a'))
#print (countnonoverlap(test,'aa'))
#print (countnonoverlap(test,'aaa'))
# ##
#
def countchar(string1):
  '''
  Name: countchar
  Function: countchar(string1)
  Input: string
  Output: integer
  Usage: print (countchar("Panagos        341234       ####$$   111"))
  Notes: Any string can be passed
  '''
    counter = 0
    for j in string1:
        counter += 1
    return counter
    
print (countchar("Panagos        341234       ####$$   111"))
def count_a(text,chara):
  '''
  Function: count_a
  Description: Counts occurrences of character, in text 
  Input: String, character
  Output: Number of encountered instances
  Usage: test(count_a("banana") == 3)
  Usage: print (count_a(text1,chara))
  '''
  count = 0
  for c in text:
    if c == str(chara):
      count += 1
  return(count)

# ########################
# Function : countconso
# Usage : countconso(string)
# Example : print countconso(string,'bob')
# Output : Counts the amount of consonants 
# Note : Pre declared consonants, all. 
# Method : Iterates over letters in string, checks if each letter exists "in" the 
# provided list, and if it does it increments the num_conso.
#
# Define Function
def countnumbers(string):
    # initialize variable
    num_numbers=0
    # iterate over string
    for char in string:
        # iterate over list of characters
        if char in "1234567890":
            num_numbers += 1
    return num_numbers

# count = str(countvowel(s))
# print ( "Number of Vowels : " + count )
# ########################
# Function : countconso
# Usage : countconso(string)
# Example : print countconso(string,'bob')
# Output : Counts the amount of consonants 
# Note : Pre declared consonants, all. 
# Method : Iterates over letters in string, checks if each letter exists "in" the 
# provided list, and if it does it increments the num_conso.
#
# Define Function
def countconso(string):
    # initialize variable
    num_conso=0
    # iterate over string
    for char in string.lower:
        # iterate over list of characters
        if char in "qrtpsdfghjklzxcvbnm":
            num_conso += 1
    return num_conso

# count = str(countconso(s))
# print ( "Number of Consonants : " + count )
# ##
#
# ########################
# Function : countany
# Usage : countany(string,letters)
# Example : print countconso(string,'bhf')
# Output : Counts the amount of all letters supplies in "letters" 
# Note : Letters must be passed encased in " "
# Method : Iterates over letters in string, checks if each letter exists "in" the 
# provided list, and if it does it increments the num_conso.
#
# Define Function
def countany(string,letters):
    # initialize variable
    num_letters=0
    # iterate over string
    for char in string:
        # iterate over list of characters
        if char in letters:
            num_letters += 1
    return num_letters

# count = str(countany(s,'brutal'))
# print ( "Number of Vowels : " + count )
# ##
#
# ###################
# Function : countalpharev
# Usage : countalpha(s) -> s = string
# Example : print (countalpha(panagos)
# Output : Longest string in reverse alphabetic order
# Note : Counts overlapping occurences
# Method : Iterates over each letter, and compares it to the next
# if the next is lexically smaller, then it sets currentsub to the concatenation
# of the two. If not it sets currentsub to the character in check and continues.
# The moment it finds a string longer than currentsub it assigns to massub.
#
# Define a new function
def countalpharev(s):
	# Initialize variables for max substring, current, and previous char
    maxSub = '' 
    currentSub = '' 
    previousChar = ''

	# Iterate over every char and check with the previous
    for char in s:
		# If current is bigger than previous, then the currentsub is the concatenation
        if char <= previousChar:
            currentSub = currentSub + char
		# If the length of current sub is greater than the max, assign
        if len(currentSub) > len(maxSub):
            maxSub = currentSub
		# If its not, then assign the value of char to currentsub
        else: currentSub = char
		# Assign char to previous char to proceed with iteration
        previousChar = char
    
    return maxSub	

	# DEBUG
# print (countalpharev(panagos)
# ##
#
# ###################
# Function : countalpha
# Usage : countalpha(s) -> s = string
# Example : print (countalpha(panagos)
# Output : Longest string in alphabetic order
# Note : Counts overlapping occurences
# Method : Iterates over each letter, and compares it to the next
# if the next is lexically bigger, then it sets currentsub to the concatenation
# of the two. If not it sets currentsub to the character in check and continues.
# The moment it finds a string longer than currentsub it assigns to massub.
#
# Define a new function
def countalpha(s):
	# Initialize variables for max substring, current, and previous char
    maxSub = '' 
    currentSub = '' 
    previousChar = ''

	# Iterate over every char and check with the previous
    for char in s:
		# If current is bigger than previous, then the currentsub is the concatenation
        if char >= previousChar:
            currentSub = currentSub + char
		# If the length of current sub is greater than the max, assign
        if len(currentSub) > len(maxSub):
            maxSub = currentSub
		# If its not, then assign the value of char to currentsub
        else: currentSub = char
		# Assign char to previous char to proceed with iteration
        previousChar = char
    
    return maxSub
    
    
# DEBUG
# print (countalpha(panagos)
def tupletostr(tuple):
  '''
  Name: tupletostr
  Function: Tuple to string
  Input: tuple
  Output: string
  Usage: b = tupletostr(tuple1)
  Notes: Any tuple can be passed
  '''
     out = ''
     for x in tuple:
         out = out + str(x)
     return out  
input = 'John,Doe,1984,4,1,male'


a = 'a;b;g;c;d'


def tokenize_string(str,delim):
  '''
  Function: tokenize_string
  Description: Tokenizes a string based on spec. delimiter
  Input: string, delimiter
  Output: List of tokens
  Usage: a = tokenize_string(string, 'delimiter')
  Notes: Parses strings
  '''
  tokens = str.split(delim)
  outlist = []
  for j in tokens:
    outlist.append(j)
  return outlist
        
        
print (tokenize_string(a,';'))
print (tokenize_string(a,'a'))
print (tokenize_string(a,','))
def todec(string1):
    '''
    Function : Converts a string to oct
    Called as : tohex(string1)
    Notes : Translates everything including special characters, newlines
    Notes: Converts to ASCII
    '''
    strout = ''
    for i in string1:
        strout += str((ord(i)))
    return strout
    #print (strout)
def strtolist(string):
    out = []
    for s in string:
        out.append(s)
    return out
def splitbyn(str, n):
  '''
  Function: splitbyn
  Description: Splits a string into substrings of n length
  Input: String, length of string
  Output: string
  Usage: print (splitbyn("panagos", 3))
  '''
    output = ''
    while str:
        output = output + str[:n] + ' '
        str = str[n:]
    return output

print (splitbyn("panagos", 3))
def replace_tab(s, tabstop = 4):
    result = str()
    for c in s:
        if c == '\t':
            while (len(result) % tabstop != 0):
                result += ' ';
        else:
            result += c    
    return result
punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

def remove_punctuation(s):
  '''
  Function: remove_punctuation
  Description: Removes all punctuation elements from string
  Input: String with punctuation
  Output: String with out punctuation
  Usage: newstr = remove_punctuation(oldstr)
  Notes: Does not edit in place
  '''
  punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
  s_sans_punct = ""
  for letter in s:
    if letter not in punctuation:
      s_sans_punct += letter
  return s_sans_punct
    
###############################3



def remove_punctuation(s):
  '''
  Function: remove_punctuation
  Description: Removes all punctuation elements from string
  Input: String with punctuation
  Output: String with out punctuation
  Usage: newstr = remove_punctuation(oldstr)
  Notes: Does not edit in place, uses import string
  '''
  import string
  s_without_punct = ""
  for letter in s:
    if letter not in string.punctuation:
      s_without_punct += letter
  return s_without_punct

test(remove_punctuation('"Well, I never did!", said Alice.') ==
                            "Well I never did said Alice")
test(remove_punctuation("Are you very, very, sure?") ==
                             "Are you very very sure")
                             
                             
##################################

#Composing together this function and the split method from the previous section makes a useful combination — we’ll clean out the punctuation, and split will clean out the newlines and tabs while turning the string into a list of words:

my_story = """
Pythons are constrictors, which means that they will 'squeeze' the life
out of their prey. They coil themselves around their prey and with
each breath the creature takes the snake will squeeze a little tighter
until they stop breathing completely. Once the heart stops the prey
is swallowed whole. The entire animal is digested in the snake's
stomach except for fur or feathers. What do you think happens to the fur,
feathers, beaks, and eggshells? The 'extra stuff' gets passed out as ---
you guessed it --- snake POOP! """

wds = remove_punctuation(my_story).split()
print(wds)

#The output:

#['Pythons', 'are', 'constrictors', ... , 'it', 'snake', 'POOP']
def removesub(x,substr):
  '''
  Function: removesub 
  Description : Removes first occurrence fo substring from string
  Input: x (string)
         substr (substring)
  Output: String with removed substring
  Usage: print (removesub("tralala","lala"))
  '''
    sublen = len(substr)
    strlen = len(x)
    loop = 0
    while loop+sublen < strlen:
        loop = loop +1;
        if x[loop:loop+sublen] == substr:
            return x[0:loop]+x[loop+sublen:strlen]
    
    
#print subsub('tototalalatolatalala','talala')

以上是关于python Python.DataTypes.Strings的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识