简体   繁体   English

遍历字符串的字符

[英]Iterating through character of string

I have a string which I need to do a certain operation on 我有一个字符串,需要对它进行某些操作

string="_,_,_,56"

When I iterate through the elements of the string I am getting an output as 当我遍历字符串的元素时,我得到的输出为

_
,
_
,
_
,
2
4

I want the output as : 我希望输出为:

_ _ _ 56

That means I do not want ',' to be considered as a character and I want the two-digit number to be considered as a single character. 这意味着我不希望将','视为一个字符,并且希望将两位数字视为一个字符。

Is it possible to achieve? 有可能实现吗?

Do this: 做这个:

string = "_,_,_,56"
new_string = string.split(",")
print(new_string)
# ['_', '_', '_', '56']

The str.split() method allows you to split a single string into a list of strings, using the given character as a separator. 使用str.split()方法,可以使用给定字符作为分隔符,将单个字符串拆分为字符串列表。

Two Three simple ways using str methods join , split and replace : 使用str方法的三种简单方法joinsplitreplace

>>> string="_,_,_,56"
>>> print(string.replace(',', ' '))
_ _ _ 56
>>> print(' '.join(string.split(',')))
_ _ _ 56

Another version thanks to @Blckknght is using the * operator to unpack the split ted list: 感谢@Blckknght的另一个版本使用*运算符解压缩split列表:

>>> print(*string.split(','))
_ _ _ 56

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM