首页 > 其他分享 >字符串内特殊字符的替换处理,如对\n的替换

字符串内特殊字符的替换处理,如对\n的替换

时间:2022-12-26 10:47:48浏览次数:42  
标签:如对 list replace 字符串 print data 替换 特殊字符

一、对于字符串特殊字符的替换

对于字符串内,\n的处理,如何去掉

s='123,456\n'
s1=s.strip('\n')
s2=s.replace('\n','')
print(s)
print(s1)
print(s2)

执行结果

123,456

123,456
123,456

strip(),能去除字符串首尾的特殊字符;而replace没有此限制

strip()的官方解释:strip()默认去除的是首尾的空白字符;如果给定的话,去除给定的字符;

    def strip(self, *args, **kwargs): # real signature unknown
        """
        Return a copy of the string with leading and trailing whitespace removed.
        
        If chars is given and not None, remove characters in chars instead.
        """

replace()的官方解释:默认用新值替换所有的出现的字符;如果给定数量,则按数量进行替换

"""
        Return a copy with all occurrences of substring old replaced by new.
        
          count
            Maximum number of occurrences to replace.
            -1 (the default value) means replace all occurrences.
        
        If the optional argument count is given, only the first count occurrences are
        replaced.
        """

如:

s='123a,a456a'

#把字符串中的字符 a 替换为字符b,只替换前2个
s3=s.replace('a','b',2)
#把字符串中的字符 a 都替换为字符b,
s4=s.replace('a','b')
print(s)
print(s3)
print(s4)

执行结果:

123a,a456a
123b,b456a
123b,b456b

 二、对于文件读取后,内容的替换

如,有个文件,text,内容如下:

1234
4567
this
ok

python的处理方法可以这样处理,代码如下:

data_list=[i.replace('\n','') for i in data_list];用了字符串的replace函数及列表推导式
with open('text') as f:
    data_list=f.readlines()
    data_list=[i.replace('\n','') for i in data_list]
    print(data_list)

执行结果:

['1234', '4567', 'this', 'ok']

 

标签:如对,list,replace,字符串,print,data,替换,特殊字符
From: https://www.cnblogs.com/yxm-yxwz/p/17005169.html

相关文章