搜索
首页后端开发Python教程Python程序:输入逗号分隔的字符串

Python程序:输入逗号分隔的字符串

Sep 09, 2023 pm 04:25 PM
python字符串输入

Python程序:输入逗号分隔的字符串

当输入文本字符串或作为输入给出时,其间可能有逗号。有时,任务是分隔句子或文本字符串的所有逗号分隔部分。这些部分可以具有单个单词或多个单词。这些字符串部分可以作为列表项进一步输入或者可以进一步处理。同样,也需要输入整数形式或小数形式的数字,并用逗号分隔。在这种情况下,将它们理解为数字很重要。本文通过使用四个不同的示例,演示了给定逗号分隔的字符串或句子或数字,并通过 Python 程序理解其逗号分隔结构来处理它的过程。

示例 1 - 输入逗号分隔字符串并使用 split 函数查找逗号分隔部分的程序

算法

第 1 步 - 首先输入一个以逗号分隔的字符串。

步骤 2 - 使用 split 函数将逗号分隔的部分分隔成列表。

第 3 步 - 删除列表项左侧的空格。

第 4 步 - 删除列表项右侧的空格。

第 5 步 - 运行程序,然后检查结果。

Python 文件包含此

commaSepStr = input ("Enter a comma separated String:")
list1 = commaSepStr.split(",")

def removeLspace(list):
   return [item.lstrip() for item in list]
    
print(commaSepStr)
print(list1)

def removeRspace(list):
   return [item.rstrip() for item in list]

noextraleftspace_list = removeLspace(list1)
noextrarightspace_list = removeRspace(noextraleftspace_list)

print(noextrarightspace_list)
print(*noextrarightspace_list, sep = "\n")

查看结果 - 示例 1

要查看结果,请在 cmd 窗口中运行 Python 文件。

Enter a comma separated String :Our last night plate included two rotis,daal,mixveg, rice, paneer, salad and achaar
Our last night plate included two rotis,daal,mixveg, rice, paneer, salad and achaar
['Our last night plate included two rotis', 'daal', 'mixveg', ' rice', ' paneer', ' salad and achaar']
['Our last night plate included two rotis', 'daal', 'mixveg', 'rice', 'paneer', 'salad and achaar']
Our last night plate included two rotis
daal
mixveg
rice
paneer
salad and achaar

示例 2:输入逗号分隔字符串并使用“for”循环查找逗号分隔部分的程序。

算法

第 1 步 - 首先给出一个以逗号分隔的输入字符串。

第 2 步 - 逐个字符地遍历字符串并识别逗号分隔的部分并将它们附加到列表中。

第 3 步 - 删除列表项左侧的空格。

第 4 步 - 打印包含没有多余空格的项目的列表。

第 5 步 - 运行程序,然后检查结果。

Python 文件包含此

commaSepStr = input ("Enter a comma separated String :")

print("The Entered String is: " + commaSepStr)
 
startofItem = 0
list1=[]
for item in range(len(commaSepStr)):
   if commaSepStr[item] == ',':
      # characters from startofItem to comma
      nospaceitem=commaSepStr[startofItem:item].lstrip()
      list1.append(nospaceitem)
      startofItem = item+1
      print(nospaceitem)

# characters from startofItem to end
nospaceitem=commaSepStr[startofItem:].lstrip()        
print(nospaceitem)
list1.append(nospaceitem)
print(list1))

查看结果

打开cmd窗口并运行python文件查看结果。

Enter a comma separated String :Our last night plate included two rotis,daal,mixveg, rice, paneer, salad and achaar
The Entered String is: Our last night plate included two rotis,daal,mixveg, rice, paneer, salad and achaar
Our last night plate included two rotis
daal
mixveg
rice
paneer
salad and achaar
['Our last night plate included two rotis', 'daal', 'mixveg', 'rice', 'paneer', 'salad and achaar']

示例 3 - 输入逗号分隔的整数字符串的程序

算法

步骤 1 - 首先输入一个以逗号分隔且仅包含整数的字符串。

第 2 步 - 使用 split 函数将逗号分隔的整数分隔成字符串列表。

第 3 步 - 从此字符串列表中获取每个项目,并将它们转换为整数类型,并将它们作为整数附加到另一个列表。

第 4 步 - 运行程序,然后检查结果。

Python 文件包含此

# input comma-separated numbers as string 
strInput = input ("Enter comma separated integers: ")
print( "Input string: ", strInput)

# convert to the list
strlist = strInput.split(",")
print("list of string type numbers: ", strlist)

# convert each string element as integers
list1 = []
for item in strlist:
	list1.append(int(item))

# print list as integers
print("list of integers: ", list1)

查看结果 - 示例 3

要查看结果,请在 cmd 窗口中运行 Python 文件。

Enter comma separated integers: 101, 280, 98, 185, 934, 9684, 955, 20, 34
Input string:  101, 280, 98, 185, 934, 9684, 955, 20, 34
list of string type numbers:  ['101', ' 280', ' 98', ' 185', ' 934', ' 9684', ' 955', ' 20', ' 34']
list of integers:  [101, 280, 98, 185, 934, 9684, 955, 20, 34]

示例 4:输入具有十进制数字的逗号分隔字符串的程序

第 1 步 - 首先输入一个以逗号分隔的字符串,并且仅包含整数和小数。

步骤 2 - 使用 split 函数来识别逗号分隔的数字并将它们作为字符串附加到列表中。

第 3 步 - 从此字符串列表中取出每个数字,并将它们转换为浮点类型,并将它们作为小数附加到另一个列表。

第 4 步 - 运行程序,然后检查结果。

Python 文件包含此

# input comma separated numbers as string 
strInput = input ("Enter comma separated numbers: ")
print( "Input string: ", strInput)

# convert to the list
strlist = strInput.split (",")
print("list of string type numbers: ", strlist)

# convert each string element as integers
list1 = []
for item in strlist:
	list1.append(float(item))

# print list as integers
print("list of decimal numbers: ", list1)

查看结果 - 示例 4

打开cmd窗口并运行python文件查看结果。

Enter comma-separated numbers: 102.88, 6.5, 6767.907, 5555.3, 4545, 6677,56.009
Input string:  102.88, 6.5, 6767.907, 5555.3, 4545, 6677,56.009
list of string type numbers:  ['102.88', ' 6.5', ' 6767.907', ' 5555.3', ' 4545', ' 6677', '56.009']
list of decimal numbers:  [102.88, 6.5, 6767.907, 5555.3, 4545.0, 6677.0, 56.009]

图 4:显示具有十进制数字的输入字符串中以逗号分隔的部分的列表。

在这篇 Python 文章中,使用四个不同的示例,给出了如何输入逗号分隔字符串的方法。首先,在示例 1 中,使用 split 函数将字符串的各个部分用逗号分隔。在示例 2 中,通过检查所有字符来遍历字符串来识别逗号分隔的部分。在示例 3 中,整数作为字符串输入,在示例 4 中,十进制数作为输入字符串给出,然后分隔到列表中。

以上是Python程序:输入逗号分隔的字符串的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
您如何将元素附加到Python列表中?您如何将元素附加到Python列表中?May 04, 2025 am 12:17 AM

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

您如何创建Python列表?举一个例子。您如何创建Python列表?举一个例子。May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

讨论有效存储和数值数据的处理至关重要的实际用例。讨论有效存储和数值数据的处理至关重要的实际用例。May 04, 2025 am 12:11 AM

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。 1)在金融中,使用内存映射文件和NumPy库可显着提升数据处理速度。 2)科研领域,HDF5文件优化数据存储和检索。 3)医疗中,数据库优化技术如索引和分区提高数据查询性能。 4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显着提升系统性能和可扩展性。

您如何创建Python数组?举一个例子。您如何创建Python数组?举一个例子。May 04, 2025 am 12:10 AM

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

使用Shebang系列指定Python解释器有哪些替代方法?使用Shebang系列指定Python解释器有哪些替代方法?May 04, 2025 am 12:07 AM

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具