Python Strings encode() method - GeeksforGeeks
文章推薦指數: 80 %
Python String encode() converts a string value into a collection of bytes, ... replace – replaces the unencodable unicode to a question mark ... Skiptocontent CoursesGeekWeek2022ForWorkingProfessionalsDSAClasses(Live)SystemDesign(Live)JavaBackendDeveloper(Live)FullStack(Live)ExploreMoreLiveCoursesDSA(Self-Paced)SDETheory(Self-Paced)AllDevelopmentCourses(Self-Paced)ExploreMoreSelf-PacedCoursesForStudentsCompetitiveProgramming(Live)GATECourse2023(Live)DataScience(Live)ExploreMoreLiveCoursesDSA(Self-Paced)CIP(Self-Paced)JAVA/Python/C++(Self-Paced)ExploreMoreSelf-PacedCoursesSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#SQLScalaPerlGoLanguageKotlinWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesBusinessStudies(Class11th)BusinessStudies(Class12th)CSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersUPSCGeographyNotesHistoryNotesScience&Tech.NotesEthicsNotesPolityNotesEconomicsNotesUPSCPreviousYearPapersSSCCGLSSCCGLSyllabusGeneralStudiesEnglishReasoningSubjectwisePracticePapersPreviousYearPapersBankingExamsSBIClerkSBIClerkSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilitySBIClerkPracticePapersSBIPOSBIPOSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilityPreviousYearPapersSBIPOPracticePapersIBPSPOIBPSPO2022SyllabusEnglishNotesReasoningNotesPreviousYearPapersMockQuestionPapersIBPSClerkIBPSClerkSyllabusEnglishNotesPreviousYearPapersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPythonStringMethodsstringcapitalize()inPythonPythonStringcasefold()MethodPythonStringcenter()MethodPythonStringcount()MethodPythonStringsencode()methodPythonStringendswith()Methodexpandtabs()methodinPythonPythonStringfind()methodPythonStringformat()MethodPythonStringformat_map()MethodPythonStringindex()MethodPythonStringisalnum()MethodPythonStringisalpha()MethodPythonstringisdecimal()MethodPythonStringisdigit()MethodPythonStringisidentifier()MethodPythonStringislower()methodPythonStringisnumeric()MethodPythonStringisprintable()MethodPythonStringisspace()MethodPythonStringistitle()MethodPythonStringisupper()methodPythonStringjoin()MethodPythonStringlower()MethodPythonStringMethodsstringcapitalize()inPythonPythonStringcasefold()MethodPythonStringcenter()MethodPythonStringcount()MethodPythonStringsencode()methodPythonStringendswith()Methodexpandtabs()methodinPythonPythonStringfind()methodPythonStringformat()MethodPythonStringformat_map()MethodPythonStringindex()MethodPythonStringisalnum()MethodPythonStringisalpha()MethodPythonstringisdecimal()MethodPythonStringisdigit()MethodPythonStringisidentifier()MethodPythonStringislower()methodPythonStringisnumeric()MethodPythonStringisprintable()MethodPythonStringisspace()MethodPythonStringistitle()MethodPythonStringisupper()methodPythonStringjoin()MethodPythonStringlower()MethodPythonStringsencode()methodViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 17Aug,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle PythonStringencode()convertsastringvalueintoacollectionofbytes,usinganencodingschemespecifiedbytheuser.PythonStringencode()MethodSyntax:Syntax:encode(encoding,errors)Parameters: encoding:Specifiestheencodingonthebasisofwhichencodinghastobeperformed. errors:Decideshowtohandletheerrorsiftheyoccur,e.g‘strict’raisesUnicodeerrorincaseofexceptionand‘ignore’ignorestheerrorsthatoccurred.Therearesixtypesoferrorresponsestrict–defaultresponsewhichraisesaUnicodeDecodeErrorexceptiononfailureignore–ignorestheunencodableunicodefromtheresultreplace–replacestheunencodableunicodetoaquestionmark?xmlcharrefreplace–insertsXMLcharacterreferenceinsteadofunencodableunicodebackslashreplace–insertsa\uNNNNescapesequenceinsteadofunencodableunicodenamereplace–insertsa\N{…}escapesequenceinsteadofunencodableunicodeReturn: ReturnsthestringintheencodedformPythonStringencode()MethodExample:Python3print("¶".encode('utf-8'))Output:b'\xc2\xb6'Example1:CodetoprintencodingschemesavailableTherearecertainencodingschemessupportedbyPythonStringencode()method.WecangetthesupportedencodingsusingthePythoncodebelow.Python3fromencodings.aliasesimportaliases #Printinglistavailableprint("Theavailableencodingsare:")print(aliases.keys())Output: Theavailableencodingsare: dict_keys(['ibm039','iso_ir_226','1140','iso_ir_110','1252','iso_8859_8','iso_8859_3','iso_ir_166','cp367','uu','quotedprintable','ibm775','iso_8859_16_2001','ebcdic_cp_ch','gb2312_1980','ibm852','uhc','macgreek','850','iso2022jp_2','hz_gb_2312','elot_928','iso8859_1','eucjp','iso_ir_199','ibm865','cspc862latinhebrew','863','iso_8859_5','latin4','windows_1253','csisolatingreek','latin5','855','windows_1256','rot13','ms1361','windows_1254','ibm863','iso_8859_14_1998','utf8_ucs2','500','iso8859','775','l7','l2','gb18030_2000','l9','utf_32be','iso_ir_100','iso_8859_4','iso_ir_157','csibm857','shiftjis2004','iso2022jp_1','iso_8859_2_1987','cyrillic','ibm861','ms950','ibm437','866','csibm863','932','iso_8859_14','cskoi8r','csptcp154','852','maclatin2','sjis','korean','865','u32','csshiftjis','dbcs','csibm037','csibm1026','bz2','quopri','860','1255','861','iso_ir_127','iso_celtic','chinese','l8','1258','u_jis','cspc850multilingual','iso_2022_jp_2','greek8','csibm861','646','unicode_1_1_utf_7','ibm862','latin2','ecma_118','csisolatinarabic','zlib','iso2022jp_3','ksx1001','858','hkscs','shiftjisx0213','base64','ibm857','maccentraleurope','latin7','ruscii','cp_is','iso_ir_101','us_ascii','hebrew','ansi_x3.4_1986','csiso2022jp','iso_8859_15','ibm860','ebcdic_cp_us','x_mac_simp_chinese','csibm855','1250','maciceland','iso_ir_148','iso2022jp','u16','u7','s_jisx0213','iso_8859_6_1987','csisolatinhebrew','csibm424','quoted_printable','utf_16le','tis260','utf','x_mac_trad_chinese','1256','cp866u','jisx0213','csiso58gb231280','windows_1250','cp1361','kz_1048','asmo_708','utf_16be','ecma_114','eucjis2004','x_mac_japanese','utf8','iso_ir_6','cp_gr','037','big5_tw','eucgb2312_cn','iso_2022_jp_3','euc_cn','iso_8859_13','iso_8859_5_1988','maccyrillic','ks_c_5601_1987','greek','ibm869','roman8','csibm500','ujis','arabic','strk1048_2002','424','iso_8859_11_2001','l5','iso_646.irv_1991','869','ibm855','eucjisx0213','latin1','csibm866','ibm864','big5_hkscs','sjis_2004','us','iso_8859_7','macturkish','iso_2022_jp_2004','437','windows_1255','s_jis_2004','s_jis','1257','ebcdic_cp_wt','iso2022jp_2004','ms949','utf32','shiftjis','latin','windows_1251','1125','ks_x_1001','iso_8859_10_1992','mskanji','cyrillic_asian','ibm273','tis620','1026','csiso2022kr','cspc775baltic','iso_ir_58','latin8','ibm424','iso_ir_126','ansi_x3.4_1968','windows_1257','windows_1252','949','base_64','ms936','csisolatin2','utf7','iso646_us','macroman','1253','862','iso_8859_1_1987','csibm860','gb2312_80','latin10','ksc5601','iso_8859_10','utf8_ucs4','csisolatin4','ebcdic_cp_be','iso_8859_1','hzgb','ansi_x3_4_1968','ks_c_5601','l3','cspc8codepage437','iso_8859_7_1987','8859','ibm500','ibm1026','iso_8859_6','csibm865','ibm866','windows_1258','iso_ir_138','l4','utf_32le','iso_8859_11','thai','864','euc_jis2004','cp936','1251','zip','unicodebigunmarked','csHPRoman8','csibm858','utf16','936','ibm037','iso_8859_8_1988','857','csibm869','ebcdic_cp_he','cp819','euccn','iso_8859_2','ms932','iso_2022_jp_1','iso_2022_kr','csisolatin6','iso_2022_jp','x_mac_korean','latin3','csbig5','hz_gb','csascii','u8','csisolatin5','csisolatincyrillic','ms_kanji','cspcp852','rk1048','iso2022jp_ext','csibm273','iso_2022_jp_ext','ibm858','ibm850','sjisx0213','tis_620_2529_1','l10','iso_ir_109','ibm1125','1254','euckr','tis_620_0','l1','ibm819','iso2022kr','ibm367','950','r8','hex','cp154','tis_620_2529_0','iso_8859_16','pt154','ebcdic_cp_ca','ibm1140','l6','csibm864','csisolatin1','csisolatin3','latin6','iso_8859_9_1989','iso_8859_3_1988','unicodelittleunmarked','macintosh','273','latin9','iso_8859_4_1988','iso_8859_9','ebcdic_cp_nl','iso_ir_144'])Example2:CodetoencodethestringPython3string="¶" #utf-8character #tryingtoencodeusingutf-8schemeprint(string.encode('utf-8'))Output:b'\xc2\xb6'ErrorswhenusingwrongencodingschemeExample1:PythonStringencode()methodwillraiseUnicodeEncodeErrorifwrongencodingschemeisusedPython3string="¶" #utf-8character #tryingtoencodeusingasciischemeprint(string.encode('ascii'))Output:UnicodeEncodeError:'ascii'codeccan'tencodecharacter'\xb6'inposition0:ordinalnotinrange(128)Example2:Using‘errors’parametertoignoreerrorswhileencodingPythonStringencode()methodwitherrorsparametersetto‘ignore’willignoretheerrorsinconversionofcharactersintospecifiedencodingscheme.Python3string="123-¶" #utf-8character #ignoreifthereareanyerrorsprint(string.encode('ascii',errors='ignore'))Output:b'123-'MyPersonalNotes arrow_drop_upSave LikePreviousPythonStringcount()MethodNext PythonStringendswith()MethodRecommendedArticlesPage:03,May1825,Mar1910,Mar2010,Mar2027,Nov1822,Sep2022,Apr1917,Dec2029,Nov1823,Feb2106,Apr1802,Jan1831,Jan1814,Mar1925,Nov1913,Jun1925,Nov1920,Sep1814,Dec1824,Dec1803,Jan1930,Mar2123,Jan1927,Feb19ArticleContributedBy:manjeet_04@manjeet_04VotefordifficultyEasy Normal Medium Hard ExpertImprovedBy:AmiyaRanjanRouttuhinmi74jnArticleTags:Python-Built-in-functionsPython-Functionspython-stringPythonPracticeTags:pythonpython-functionsReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python String encode() Method - W3Schools
- 2Unicode & Character Encodings in Python: A Painless Guide
Unicode vs UTF-8; Encoding and Decoding in Python 3; Python 3: All-In on ... is a way of specifyi...
- 3How to encode a string as UTF-8 in Python - Adam Smith
- 4python3 encode replace unicode characters - Stack Overflow
To be totally honest, I want to convert the unicode characters to their xmlcharref, keeping every...
- 5Python Strings encode() method - GeeksforGeeks
Python String encode() converts a string value into a collection of bytes, ... replace – replaces...