I try to figure out how I can delete certain characters from a string. Unfortunately, it doesn't work. I would appreciate all the help.
def delete_char(string):
string = list(string)
string.remove("\n")
return ''.join(string)
delete_char("I want \n to test \n if you \n work")
How about using replace, instead?
def delete_char(string, target_char, replacement_char=""):
return string.replace(target_char, replacement_char)
print(delete_char("I want \n to test \n if you \n work", "\n"))
You need to re-assign the string value to the removed form. Additionally I would suggest using replace instead of remove in this place, and replacing it with an empty character. Something like this should work:
def delete_char(string):
string = string.replace("\n", "")
return string
You could use str.split and str.join:
>>> ' '.join("I want \n to test \n if you \n work".split())
I want to test if you work
This isn't the same as just removing the newline character but it will ensure only one space between words.
Otherwise just replace the newline with nothing:
>>> "I want \n to test \n if you \n work".replace('\n', '')
I want to test if you work
Related
This is a Kata challenge. The function should return a string with spaces between each character. So "Hi there" should equal the the string with spaces between each letter, two spaces between the words. My code actually works in my Python environment, but it is not accepted on Kata.
def spacing(string):
return " ".join(a for a in string).split(string)
A string when iterated over is considered a sequence of characters, so you can simply pass the string to the join method directly:
def spacing(string):
return ' '.join(string)
try
def spacing(string):
return " ".join(string.replace(" ", ""))
this will work if the only whitespaces in string are spaces.
If I have a multiline string that contains "\n" as part of the text itself, for example:
python_text = """
#commands.command()
def multi():
print("Three\nLines\nHere")
"""
How can I remove all newlines except those in the text itself? I've tried creating a list with splitlines() but the multiline string will also be split on the \n's in the text itself. Using splitlines(True) in combination with strip() doesn't work for the same reasons.
print(python_text.splitlines())
Output (formatted):
[
'#commands.command()',
'def multi():',
' print("Three',
'Lines',
'Here")'
]
Whilst my desired output is:
[
'#commands.command()',
'def multi():',
' print("Three\nLines\nHere")'
]
(Or a multiline string print instead of list print, but in the same format)
Is there any way I can only strip the 'trailing' newline characters from a multiline string?
If anything is unclear please let me know and I'll try to explain further.
Edit: Corrected explanation about splitlines() and strip().
You have to escape your newlines. In this case you can just make it a raw string literal:
python_text = r"""
#commands.command()
def multi():
print("Three\nLines\nHere")
"""
print(python_text.splitlines())
>>>['', '#commands.command()', 'def multi():', ' print("Three\\nLines\\nHere")']
my code like this
import os,sys,re,string,types
cved = [
u'Python\u662fPython\u8f6f\u4ef6\u57fa\u91d1\u4f1a\u7684\u4e00\u5957\u5f00\u6e90\u7684\u3001\u9762\u5411\u5bf9\u8c61\u7684\u7a0b\u5e8f\u8bbe\u8ba1\u8bed\u8a00\u3002\u8be5\u8bed\u8a00\u5177\u6709\u53ef\u6269\u5c55\u3001\u652f\u6301\u6a21\u5757\u548c\u5305\u3001\u652f\u6301\u591a\u79cd\u5e73\u53f0\u7b49\u7279\u70b9\u3002\r',
u'Python\u7684Modules/socketmodule.c\u6587\u4ef6\u4e2d\u7684\u2018socket.recvfrom_into\u2019\u51fd\u6570\u5b58\u5728\u7f13\u51b2\u533a\u6ea2\u51fa\u6f0f\u6d1e\u3002\u8fdc\u7a0b\u653b\u51fb\u8005\u53ef\u501f\u52a9\u7279\u5236\u7684\u5b57\u7b26\u4e32\u5229\u7528\u8be5\u6f0f\u6d1e\u6267\u884c\u4efb\u610f\u4ee3\u7801\u3002\u4ee5\u4e0b\u7248\u672c\u53d7\u5230\u5f71\u54cd\uff1aPython 2.7.7\u4e4b\u524d\u76842.5\u7248\u672c\uff0c3.3.4\u4e4b\u524d\u76843.x\u7248\u672c\uff0c3.4rc1\u4e4b\u524d\u76843.4.x\u7248\u672c\u3002', u'\u76ee\u524d\u5382\u5546\u5df2\u7ecf\u53d1\u5e03\u4e86\u5347\u7ea7\u8865\u4e01\u4ee5\u4fee\u590d\u6b64\u5b89\u5168\u95ee\u9898\uff0c\u8865\u4e01\u83b7\u53d6\u94fe\u63a5\uff1a\r'
]
print "".join(cved)
why is the first unicode value not printed?
The output is:
Python的Modules/socketmodule.c文件中的‘socket.recvfrom_into’函数存在缓冲区溢出漏洞。远程攻击者可借助特制的字符串利用该漏洞执行任意代码。以下版本受到影响:Python 2.7.7之前的2.5版本,3.3.4之前的3.x版本,3.4rc1之前的3.4.x版本。目前厂商已经发布了升级补丁以修复此安全问题,补丁获取链接:
Where did the Python是Python软件基金会的一套开源的、面向对象的程序设计语言。该语言具有可扩展、支持模块和包、支持多种平台等特点 text go?
Your string includes \r carriage return values, causing the first element to be overwritten by the second. The carriage return causes the terminal to move the cursor to the start of the line and any subsequent characters overwrite what was printed first.
Strip those \r characters first:
print u"".join([s.rstrip('\r') for s in cved])
I used str.rstrip() to remove those characters from the end; if you have the same characters in the middle of your text, you could use str.translate() instead:
print u"".join([s.translate({13: None}) for s in cved])
character = (%.,-();'0123456789-—:`’)
character.replace(" ")
character.delete()
I want to delete or replace all the special characters and numbers from my program, I know it can be done in the one string just not sure how to space all the special characters with quotes or anything. Somehow I'm supposed to separate all the special character in the parenthesis just not sure how to break up and keep all the characters stored in the variable.
The translate method is my preferred way of doing this. Create a mapping between the chars you want mapped and then apply that table to your input string.
from string import maketrans
special = r"%.,-();'0123456789-—:`’"
blanks = " " * len(special)
table = maketrans(special, blanks)
input_string.translate(table)
Seems like a good application for filter
>>> s = 'This is a test! It has #1234 and letters?'
>>> filter(lambda i: i.isalpha(), s)
'ThisisatestIthasandletters'
You can have a function with an optional fill value, if not set it will just delete/remove the non alpha characters or you can specify a default replace value:
def delete_replace(s,fill_char = ""):
return "".join([x if x.isalpha() else fill_char for x in s])
I have the string name = 'one two'. i want to make 'onetwo' from it.
is there any cool python shortcut for it like .join() but without space?
You can do name.replace(' ','') or ''.join(name.split())
You could do this by just striping all whitespace in a string:
name.replace(" ", "")
How about "".join(name.split(" ")) ?
Another one, only using one empty string and no explicit whitespace:
"".join('one two'.split())
Result:
'onetwo'