While running code I got an output,
vivek
Hello World!
There is a line break between "vivek" and "hello World", but I want an output without a line break
vivek
Hello World
like above
# Hello World program in Python
arr =['vivek\n','singh\n']
arr[0].replace('\n','')
print arr[0]
print "Hello World!"
Just replace the line
arr[0].replace('\n','')
by
arr[0] = arr[0].replace('\n', '')
as str.replace does only return a modified copy and not modify the original. See str.replace documentation.
Other suggestions
You could also use str.strip to remove surrounding whitespaces. A neat way to remove all surrounding whitespaces for a list is
yourlist = [strelement.strip() for strelement in yourlist]
This is called a list comprehension.
You might also want to use print as a function instead of a statement. So you use print("whatever") instead of print "whatever". The print function works with Python 2 and Python 3, whereas the statement works only in Python 2.
Then you might want to take a look at http://pep8online.com/ and https://www.python.org/dev/peps/pep-0008/
Because attr[0] is a string, string.replace just return a copy of updated string, but not change original string.
You can also remove using Regular Expression:
>>> import re
>>> result = re.sub(u"\u005cn", r"", "vivek\n Hello World!")
>>> result
'Vivek Hello World!'
You can also do split and join that will remove the new line from the list:
arr = ['vivek\n', 'singh\n']
arr = ''.join(arr).split('\n')
print(arr[0] + " Hello World!")
or
print(arr[0])
print(" Hello World!")
The question is about removing the new line from the strings in the list. split and join is the most pythonic way available to do so.
You can use regular expressions to filter out unwanted characters from your string.
import re
s = "hello\nworld"
print re.sub(r'\n',' ',s)
will return : "hello world"
So you need to just do
print re.sub(r'\n','',arr[0])
Related
I have a list l.
l = ["This is","'the first 'string","and 'it is 'good"]
I want to replace all the whitespaces with "|space|" in strings that are within 's.
print (l)
# ["This is","'the|space|first|space|'string","and 'it|space|is|space|'good"]
I can't use a for loop inside a for loop and directly use .replace() as strings are not mutable
TypeError: 'str' object does not support item assignment
I have seen the below questions and none of them have helped me.
Replacing string element in for loop Python (3 answers)
Running replace() method in a for loop? (3 answers)
Replace strings using List Comprehensions (7 answers)
I have considered using re.sub but can't think of a suitable regular expression that does the job.
This works for me:
>>> def replace_spaces(str) :
... parts = str.split("'")
... for i in range(1,len(parts),2) :
... parts[i] = parts[i].replace(' ', '|')
... return "'".join( parts )
...
>>> [replace_spaces(s) for s in l]
['This is', "'the|first|'string", "and 'it|is|'good"]
>>>
I think I have solved your replacing problem with regex. You might have to polish the given code snippet a bit more to suit your need.
If I understood the question correctly, the trick was to use a regular expression to find the right space to be replaced.
match = re.findall(r"\'(.+?)\'", k) #here k is an element in list.
Placing skeleton code for your reference:
import re
l = ["This is","'the first 'string","and 'it is 'good"]
#declare output
for k in l:
match = re.findall(r"\'(.+?)\'", k)
if not match:
#append k itself to your output
else:
p = (str(match).replace(' ', '|space|'))
#append p to your output
I haven't tested it yet, but it should work. Let me know if you face any issues with this.
Using regex text-munging :
import re
l = ["This is","'the first 'string","and 'it is 'good"]
def repl(m):
return m.group(0).replace(r' ', '|space|')
l_new = []
for item in l:
quote_str = r"'.+'"
l_new.append(re.sub(quote_str, repl, item))
print(l_new)
Output:
['This is', "'the|space|first|space|'string", "and 'it|space|is|space|'g
ood"]
Full logic is basically:
Loop through elements of l.
Find the string between single quotes. Pass that to repl function.
repl function I'm using simple replace to replace spaces with |space| .
Reference for text-munging => https://docs.python.org/3/library/re.html#text-munging
pattern = "world! {} "
text = "hello world! this is python"
Given the pattern and text above, how do I produce a function that would take pattern as the first argument and text as the second argument and output the word 'this'?
eg.
find_variable(pattern, text) ==> returns 'this' because 'this'
You may use this function that uses string.format to build a regex with a single captured group:
>>> pattern = "world! {} "
>>> text = "hello world! this is python"
>>> def find_variable(pattern, text):
... return re.findall(pattern.format(r'(\S+)'), text)[0]
...
>>> print (find_variable(pattern, text))
this
PS: You may want to add some sanity checks inside your function to validate string format and a successful findall.
Code Demo
Not a one liner like anubhava's but using basic python knowledge:
pattern="world!"
text="hello world! this is python"
def find_variabel(pattern,text):
new_text=text.split(' ')
for x in range(len(new_text)):
if new_text[x]==pattern:
return new_text[x+1]
print (find_variabel(pattern,text))
I am trying to split a string but it should be replaced to another string and return as a list. Its hard to explain so here is an example:
I have string in variable a:
a = "Hello World!"
I want a list such that:
a.split("Hello").replace("Hey") == ["Hey"," World!"]
It means I want to split a string and write another string to that splited element in the list. SO if a is
a = "Hello World! Hello Everybody"
and I use something like a.split("Hello").replace("Hey") , then the output should be:
a = ["Hey"," World! ","Hey"," Everybody"]
How can I achieve this?
From your examples it sounds a lot like you want to replace all occurrences of Hello with Hey and then split on spaces.
What you are currently doing can't work, because replace needs two arguments and it's a method of strings, not lists. When you split your string, you get a list.
>>> a = "Hello World!"
>>> a = a.replace("Hello", "Hey")
>>> a
'Hey World!'
>>> a.split(" ")
['Hey', 'World!']
x = "HelloWorldHelloYou!"
y = x.replace("Hello", "\nHey\n").lstrip("\n").split("\n")
print(y) # ['Hey', 'World', 'Hey', 'You!']
This is a rather brute-force approach, you can replace \n with any character you're not expecting to find in your string (or even something like XXXXX). The lstrip is to remove \n if your string starts with Hello.
Alternatively, there's regex :)
this functions can do it
def replace_split(s, old, new):
return sum([[blk, new for blk] in s.split(old)], [])[:-1]
It wasnt clear if you wanted to split by space or by uppercase.
import re
#Replace all 'Hello' with 'Hey'
a = 'HelloWorldHelloEverybody'
a = a.replace('Hello', 'Hey')
#This will separate the string by uppercase character
re.findall('[A-Z][^A-Z]*', a) #['Hey', 'World' ,'Hey' ,'Everybody']
You can do this with iteration:
a=a.split(' ')
for word in a:
if word=='Hello':
a[a.index(word)]='Hey'
I want to print the output but without parenthesis. This my example code.
asa = 13
a = "Hello, World! ", asa, "Year"
print(a)
This the output i get:
('Hello, World! ', 13, 'Year')
I want to print the sentence without '' and () also ,
You should use + operator to concatenate strings, and turn non-string objects (like int) into strings by using str(object):
asa = 13
a = "Hello, World! "+ str(asa)+ "Year"
print(a)
Alternatively you could use string formatting:
asa = 13
a = "Hello, World! {n} Year".format(n=asa)
print(a)
The parentheses are because you've created "a" as a tuple and tuples are represented with parenthesis, the same way dicts are represented with curly brackets and lists with square brackets.
Make a into a proper string instead, using the suggestions in #ibarrond's answer, or like this:
asa = 13
a = "Hello, World! %dYear"
print(a % asa) # output: "Hello, World! 13Year"
I suspect you want a space after %d, but that's not how you wrote your code.
#afifizain
Your code is also correct.
Let me explain you why you are getting '' () and , in your print statement.
You have assigned values to variable a with comma separator, so your variable 'a' is not a string, it is tuple
you can simply pass your values to print function directly instead of storing them in variable a, it will work. You can print it like below.
print("Hello, World! ", asa, "Year" )
But if you compulsory want to store values in variable 'a' then you need to unpack those values with using * like below.
print(*a)
The pythonic way of doing this in python 3.6 is:
print(f'Hello, World! {asa}Year')
Okay, so I have this text file:
hello there hello print hello there print lolol
this is what I want to do in Python(down below in pseudo-code):
when print statement found:
print next five letters(not including space);
This is the result I want:
>>>[hello, lolol]
How do I solve this problem in python?
If there are always 5 letters that follow a print and a space, you can use the following regex with lookbehind:
import re
print(re.findall(r'(?<=\bprint ).{5}', 'hello there hello print hello there print lolol'))
This outputs:
['hello', 'lolol']
split by 'print ' and use list indexing to get the first 5 characters of the string
In [253]: [res[:5] for res in s.split('print ')[1:]]
Out[253]: ['hello', 'lolol']