Python string.replace() Examples

The following are 30 code examples of string.replace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: smb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def check_dir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            smb['Mid'] = 0

            cmd = SMBCommand(SMB.SMB_COM_CHECK_DIRECTORY)
            cmd['Parameters'] = ''
            cmd['Data'] = SMBCheckDirectory_Data(flags = self.__flags2)
            cmd['Data']['DirectoryName'] = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path
            smb.addCommand(cmd)

            self.sendSMB(smb)

            while 1:
                s = self.recvSMB()
                if s.isValidAnswer(SMB.SMB_COM_CHECK_DIRECTORY):
                    return
        finally:
            self.disconnect_tree(tid) 
Example #2
Source File: 9.py    From Python-John-Zelle-book with MIT License 6 votes vote down vote up
def main():
    print "This program converts a textual message into a sequence"
    print "of numbers representing the ASCII encoding of the message."
    print
    
    # Get the message to encode
    message = raw_input("Please enter the message to encode: ")
    n = int(raw_input("Enter the key value"))
    print
    print "Here are the ASCII codes:"
    z = string.replace(message,"z","a")
    z1 = string.replace(z,"Z","A")
    
    # Loop through the message and print out the ASCII values
    for ch in z1:
        a = chr(ord(ch) + n),   # use comma to print all on one line.
        print " ".join(a),
    print 
Example #3
Source File: wordnet.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example #4
Source File: serviceinstall.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def copy_file(self, src, tree, dst):
        LOG.info("Uploading file %s" % dst)
        if isinstance(src, str):
            # We have a filename
            fh = open(src, 'rb')
        else:
            # We have a class instance, it must have a read method
            fh = src
        f = dst
        pathname = string.replace(f,'/','\\')
        try:
            self.connection.putFile(tree, pathname, fh.read)
        except:
            LOG.critical("Error uploading file %s, aborting....." % dst)
            raise
        fh.close() 
Example #5
Source File: wntools.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 
Example #6
Source File: smb3.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def mkdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)          
        finally:
            if fileId is not None:
                self.close(treeId, fileId)            
            self.disconnectTree(treeId) 

        return True 
Example #7
Source File: smb3.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def rmdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                                 shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                                 creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
                                 creationDisposition=FILE_OPEN, fileAttributes=0)
            from impacket import smb
            delete_req = smb.SMBSetFileDispositionInfo()
            delete_req['DeletePending'] = True
            self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return True 
Example #8
Source File: smb3.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
        # ToDo: Handle situations where share is password protected
        path = string.replace(path,'/', '\\')
        path = ntpath.normpath(path)
        if len(path) > 0 and path[0] == '\\':
            path = path[1:]

        treeId = self.connectTree(shareName)
        fileId = None
        try:
            fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
            finished = False
            writeOffset = offset
            while not finished:
                data = callback(self._Connection['MaxWriteSize'])
                if len(data) == 0:
                    break
                written = self.write(treeId, fileId, data, writeOffset, len(data))
                writeOffset += written
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 
Example #9
Source File: wordnet.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example #10
Source File: smb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def rmdir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        # Check that the directory exists
        self.check_dir(service, path, password)

        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path

            smb = NewSMBPacket()
            smb['Tid'] = tid
            createDir = SMBCommand(SMB.SMB_COM_DELETE_DIRECTORY)
            createDir['Data'] = SMBDeleteDirectory_Data(flags=self.__flags2)
            createDir['Data']['DirectoryName'] = path
            smb.addCommand(createDir)

            self.sendSMB(smb)

            while 1:
                s = self.recvSMB()
                if s.isValidAnswer(SMB.SMB_COM_DELETE_DIRECTORY):
                    return
        finally:
            self.disconnect_tree(tid) 
Example #11
Source File: dotabase.py    From MangoByte with MIT License 6 votes vote down vote up
def get_chatwheel_sound(self, text, loose_fit=False):
		def simplify(t):
			t = re.sub(r"[?!',!?.-]", "", t.lower())
			return re.sub(r"[_,]", " ", t)
		text = simplify(text)
		if text == "":
			return None
		for message in session.query(ChatWheelMessage):
			if message.sound:
				strings = list(map(simplify, [ message.name, message.message, message.label ]))
				if text in strings:
					return message
				if loose_fit:
					for string in strings:
						if text.replace(" ", "") == string.replace(" ", ""):
							return message
					for string in strings:
						if text in string:
							return message
		return None 
Example #12
Source File: wntools.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 
Example #13
Source File: smb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def rename(self, service, old_path, new_path, password = None):
        old_path = string.replace(old_path,'/', '\\')
        new_path = string.replace(new_path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            smb['Mid'] = 0

            renameCmd = SMBCommand(SMB.SMB_COM_RENAME)
            renameCmd['Parameters'] = SMBRename_Parameters()
            renameCmd['Parameters']['SearchAttributes'] = ATTR_SYSTEM | ATTR_HIDDEN | ATTR_DIRECTORY
            renameCmd['Data'] = SMBRename_Data(flags = self.__flags2)
            renameCmd['Data']['OldFileName'] = old_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else old_path
            renameCmd['Data']['NewFileName'] = new_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else new_path
            smb.addCommand(renameCmd)

            self.sendSMB(smb)

            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_RENAME):
               return 1
            return 0
        finally:
            self.disconnect_tree(tid) 
Example #14
Source File: platform.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _platform(*args):

    """ Helper to format the platform string in a filename
        compatible format e.g. "system-version-machine".
    """
    # Format the platform string
    platform = string.join(
        map(string.strip,
            filter(len, args)),
        '-')

    # Cleanup some possible filename obstacles...
    replace = string.replace
    platform = replace(platform,' ','_')
    platform = replace(platform,'/','-')
    platform = replace(platform,'\\','-')
    platform = replace(platform,':','-')
    platform = replace(platform,';','-')
    platform = replace(platform,'"','-')
    platform = replace(platform,'(','-')
    platform = replace(platform,')','-')

    # No need to report 'unknown' information...
    platform = replace(platform,'unknown','')

    # Fold '--'s and remove trailing '-'
    while 1:
        cleaned = replace(platform,'--','-')
        if cleaned == platform:
            break
        platform = cleaned
    while platform[-1] == '-':
        platform = platform[:-1]

    return platform 
Example #15
Source File: myparser.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def people_linkedin(self):
        reg_people = re.compile('">[a-zA-Z0-9._ -]* \| LinkedIn')
        #reg_people = re.compile('">[a-zA-Z0-9._ -]* profiles | LinkedIn')
        self.temp = reg_people.findall(self.results)
        resul = []
        for x in self.temp:
            y = string.replace(x, ' | LinkedIn', '')
            y = string.replace(y, ' profiles ', '')
            y = string.replace(y, 'LinkedIn', '')
            y = string.replace(y, '"', '')
            y = string.replace(y, '>', '')
            if y != " ":
                resul.append(y)
        return resul 
Example #16
Source File: dotabase.py    From MangoByte with MIT License 5 votes vote down vote up
def get_wiki_url(self, obj):
		if isinstance(obj, Hero):
			wikiurl = obj.localized_name
		elif isinstance(obj, Ability):
			wikiurl = f"{obj.hero.localized_name}#{obj.localized_name}"
		elif isinstance(obj, Item):
			wikiurl = obj.localized_name

		wikiurl = wikiurl.replace(" ", "_").replace("'", "%27")
		return f"http://dota2.gamepedia.com/{wikiurl}" 
Example #17
Source File: myparser.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def people_jigsaw(self):
        res = []
        #reg_people = re.compile("'tblrow' title='[a-zA-Z0-9.-]*'><span class='nowrap'/>")
        reg_people = re.compile(
            "href=javascript:showContact\('[0-9]*'\)>[a-zA-Z0-9., ]*</a></span>")
        self.temp = reg_people.findall(self.results)
        for x in self.temp:
            a = x.split('>')[1].replace("</a", "")
            res.append(a)
        return res 
Example #18
Source File: myparser.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def set(self):
        reg_sets = re.compile('>[a-zA-Z0-9]*</a></font>')
        self.temp = reg_sets.findall(self.results)
        sets = []
        for x in self.temp:
            y = string.replace(x, '>', '')
            y = string.replace(y, '</a</font', '')
            sets.append(y)
        return sets 
Example #19
Source File: myparser.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def profiles(self):
        reg_people = re.compile('">[a-zA-Z0-9._ -]* - <em>Google Profile</em>')
        self.temp = reg_people.findall(self.results)
        resul = []
        for x in self.temp:
            y = string.replace(x, ' <em>Google Profile</em>', '')
            y = string.replace(y, '-', '')
            y = string.replace(y, '">', '')
            if y != " ":
                resul.append(y)
        return resul 
Example #20
Source File: myparser.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def genericClean(self):
		self.results = re.sub('<em>', '', self.results)
		self.results = re.sub('<b>', '', self.results)
		self.results = re.sub('</b>', '', self.results)
		self.results = re.sub('</em>', '', self.results)
		self.results = re.sub('%2f', ' ', self.results)
		self.results = re.sub('%3a', ' ', self.results)
		self.results = re.sub('<strong>', '', self.results)
		self.results = re.sub('</strong>', '', self.results)	
		self.results = re.sub('<w:t>',' ',self.results)


		for e in ('>',':','=', '<', '/', '\\',';','&','%3A','%3D','%3C'):
			self.results = string.replace(self.results, e, ' ') 
Example #21
Source File: xmlrpclib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def escape(s, replace=string.replace):
    s = replace(s, "&", "&amp;")
    s = replace(s, "<", "&lt;")
    return replace(s, ">", "&gt;",) 
Example #22
Source File: myparser.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def people_linkedin(self):
		reg_people = re.compile('">[a-zA-Z0-9._ -]* profiles | LinkedIn')
		
		self.temp = reg_people.findall(self.results)
		resul = []
		for x in self.temp:
				y = string.replace(x, '  LinkedIn', '')
				y = string.replace(y, ' profiles ', '')
				y = string.replace(y, 'LinkedIn', '')
				y = string.replace(y, '"', '')
				y = string.replace(y, '>', '')
				if y !=" ":
					resul.append(y)
		return resul 
Example #23
Source File: string_tests.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_maketrans(self):
        self.assertEqual(
           ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
           string.maketrans('abc', 'xyz')
        )
        self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw') 
Example #24
Source File: string_tests.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_replace_overflow(self):
        # Check for overflow checking on 32 bit machines
        A2_16 = "A" * (2**16)
        self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
        self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
        self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16) 
Example #25
Source File: msvccompiler.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def sub(self, s):
        for k, v in self.macros.items():
            s = string.replace(s, k, v)
        return s 
Example #26
Source File: xmlrpclib.py    From meddle with MIT License 5 votes vote down vote up
def escape(s, replace=string.replace):
    s = replace(s, "&", "&amp;")
    s = replace(s, "<", "&lt;")
    return replace(s, ">", "&gt;",) 
Example #27
Source File: smb.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def remove(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        # Perform a list to ensure the path exists
        self.list_path(service, path, password)

        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            smb['Mid'] = 0

            cmd = SMBCommand(SMB.SMB_COM_DELETE)
            cmd['Parameters'] = SMBDelete_Parameters()
            cmd['Parameters']['SearchAttributes'] = ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE
            cmd['Data'] = SMBDelete_Data(flags = self.__flags2)
            cmd['Data']['FileName'] = (path + '\x00').encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else (path + '\x00')
            smb.addCommand(cmd)

            self.sendSMB(smb)

            while 1:
                s = self.recvSMB()
                if s.isValidAnswer(SMB.SMB_COM_DELETE):
                    return
        finally:
            self.disconnect_tree(tid) 
Example #28
Source File: platform.py    From meddle with MIT License 5 votes vote down vote up
def _syscmd_file(target,default=''):

    """ Interface to the system's file command.

        The function uses the -b option of the file command to have it
        ommit the filename in its output and if possible the -L option
        to have the command follow symlinks. It returns default in
        case the command should fail.

    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    target = _follow_symlinks(target).replace('"', '\\"')
    try:
        f = os.popen('file "%s" 2> %s' % (target, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = string.strip(f.read())
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output

### Information about the used architecture

# Default values for architecture; non-empty strings override the
# defaults given as parameters 
Example #29
Source File: platform.py    From meddle with MIT License 5 votes vote down vote up
def _platform(*args):

    """ Helper to format the platform string in a filename
        compatible format e.g. "system-version-machine".
    """
    # Format the platform string
    platform = string.join(
        map(string.strip,
            filter(len, args)),
        '-')

    # Cleanup some possible filename obstacles...
    replace = string.replace
    platform = replace(platform,' ','_')
    platform = replace(platform,'/','-')
    platform = replace(platform,'\\','-')
    platform = replace(platform,':','-')
    platform = replace(platform,';','-')
    platform = replace(platform,'"','-')
    platform = replace(platform,'(','-')
    platform = replace(platform,')','-')

    # No need to report 'unknown' information...
    platform = replace(platform,'unknown','')

    # Fold '--'s and remove trailing '-'
    while 1:
        cleaned = replace(platform,'--','-')
        if cleaned == platform:
            break
        platform = cleaned
    while platform[-1] == '-':
        platform = platform[:-1]

    return platform 
Example #30
Source File: msvccompiler.py    From meddle with MIT License 5 votes vote down vote up
def sub(self, s):
        for k, v in self.macros.items():
            s = string.replace(s, k, v)
        return s