猿问

将列表转换为小写

我正在尝试在input.txt中获得此字词列:


Suzuki music

Chinese music

Conservatory

Blue grass

Rock n roll

Rhythm

Composition

Contra

Instruments 

转换成这种格式:


"suzuki music", "chinese music", "conservatory music", "blue grass", "rock n roll", "rhythm"...

这段代码:


with open ('artsplus_stuff.txt', 'r') as f:

    list.append(", ".join(['%s' % row for row in f.read().splitlines()]))

    for item in list:

        item.lower()


print list

返回列表,但首字母大写。


['铃木音乐,中国音乐,音乐学院,蓝草,摇滚乐,节奏,作曲,打击乐,乐器']


我该如何将所有项目转换为小写?


收到一只叮咚
浏览 278回答 3
3回答

慕森王

ChessGuitarWoodworkingGardeningCar_restorationMetalworkingMarksmanCampingBackpacking_(wilderness)HuntingFishingWhittlingGeocachingSportsModel_BuildingLeatherworkingBowlingArcheryHikingConnoisseurPhotographyPool_(cue_sports)MountaineeringCookingBlacksmithAviatorMagic_(illusion)Foreign_languageCard_gameBlogPaintballFencingBrewingAmateur_AstronomyGenealogyAdventure_racingKnittingComputer_ProgrammingAmateur_radioAudiophileBakingBboyingBaton_twirlingChainmailConstructed_languageColoringCrochetingCreative_writingDrawingFantasy_FootballFishkeepingHome_automationHome_MoviesJewelryKnappingLapidary_clubLocksportMusical_InstrumentsPaintingRC_carsScrapbookingSculptingSewingSingingWritingAir_sportsBoardsportBackpackingBonsaiCanoeingCyclingDrivingFreerunningJoggingKayakingMotor_sportsMountain_bikingMachiningParkourRock_climbingRunningSailingSand_castleScullingRowing_(sport)Human_swimmingTai_ChiVehicle_restorationWater_sportsAntiquesCoin_collectingElement_collectingStamp_collectingVintage_carVintage_clothingRecord_CollectingAntiquitiesCar_audioFossil_collectingInsect_collectingLeafMetal_detectoristMineral_collectingPetalRock_(geology)SeaglassSeashellBoxingCombination_puzzleContract_BridgeCue_sportsDartsTable_footballTeam_HandballAirsoftAmerican_footballAssociation_footballAuto_racingBadmintonClimbingCricketDisc_golfFigure_skatingFootbagKart_racingPlank_(exercise)RacquetballRugby_leagueTable_tennisMicroscopyReading_(process)Shortwave_listeningVideophileAircraft_spottingAmateur_geologyBirdwatchingBus_spottingGongoozlerMeteorologyTravelBoard_gameAirbrushAdvocacyActingmodel_aircraftPetsAquariumAstrologyAstronomyBackgammonBase_JumpingSun_tanningBeachcombingBeadworkBeatboxingCampanologyBelly_dancecycle_PoloBicycle_motocrossBoatingBoomerangVolunteeringCarpentryButterfly_WatchingButton_CollectingCake_DecoratingCalligraphyCandleCartoonistCasinoCave_DivingCeramicChurchCigar_SmokingCloud_WatchingAntiqueHatalbumGramophone_recordtrading_cardMusical_compositionWorldbuildingCosplayCraftCross-StitchCrossword_PuzzleDiecastDigital_PhotographyDodgeballDollDominoesDumpster_DivingrestauranteducationElectronicsEmbroideryEntertainmentphysical_exerciseFalconryList_of_fastest_production_carsFeltPoi_(performance_art)FloorballFloristryFly_Tyingoff-roadingultimate_(sport)GameGarage_saleGhost_HuntingGlowstickingGunsmithGyotakuHandwritingHang_glidingHerpingHomeBrewingHome_RepairHome_TheaterHot_air_ballooningHula_HoopIce_skatingImpersonatorInternetInventionJewelleryJigsaw_PuzzleJugglingdiaryskipping_ropeamateur_ChemistryKitesnowkitingknotLaserLawn_DartpokerLeather_craftingLegoMacraméModel_CarMatchstick_ModelMeditationMetal_DetectorRail_transport_modellingModel_Rocketship_modelscale_modelMotorcycleNeedlepointOrigamiPapermakingPapier-mâchéParachutingParaglidingPinochlePipe_SmokingPotteryPowerbockingDemonstration_(people)PuppetryPyrotechnicsQuiltingpigeon_racingRaftingRailfanRappingremote_controlRelaxationRenaissance_FairRenting_moviesRoboticsRock_BalancingRole-playingsand_art_and_playScuba_DivingSelf-DefenseSkeet_ShootingSkiingShoppingchoirSkateboardingSketch_(drawing)SlackLiningSleepSlingshotSlot_Car_RacingSnorkelingSoapRubik's_CubecavingFamilyStorm_ChasingStorytellingString_FigureSurf_FishingSurvival_skillsTattingTaxidermyTea_TastingTesla_CoilTetrisTextilestone_RubbingAntique_toolToyTreasure_HuntingTrekkietutoringUrban_ExplorationVideo_GameViolinVolunteerWalkingWeightliftingWindsurfingWineMakingWrestlingZip-linetraveling错误:list.append(“,” .join(['“%s”'f.read()。splitlines()])中行的%类型错误:描述符'append'需要一个'list'对象,但已收到'str'注销

幕布斯6054654

代替for item in list:     item.lower()将变量的名称更改list为l或在Python中不是保留字的任何内容,并使用以下行,显然用您为列表命名的任何内容l。l = [item.lower() for item in l]该lower方法以所有小写字母返回字符串的副本。创建字符串后,没有任何内容可以修改其内容,因此您需要创建一个包含所需内容的新字符串。

白衣染霜花

这是可以做到的:In [6]: l = ['Suzuki music', 'Chinese music', 'Conservatory', 'Blue grass']In [7]: map(str.lower, l)Out[7]: ['suzuki music', 'chinese music', 'conservatory', 'blue grass']您的代码无法按预期方式运行的原因之一是item.lower()不会修改字符串(在Python中,字符串是不可变的)。而是返回字符串的小写版本,然后您的代码将其忽略。
随时随地看视频慕课网APP

相关分类

Python
我要回答