Adding a space between string words - python

Write a function named string_processing that takes a list of
strings as input and returns an all-lowercase string with no
punctuation. There should be a space between each word. You do not
have to check for edge cases.
Here is my code:
import string
def string_processing(string_list):
str1 = ""
for word in string_list:
str1 += ''.join(x for x in word if x not in string.punctuation)
return str1
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
My output:
'helloworld'
'testmeplease'
Expected output:
'hello world'
'test me please'
How to add a space in just between words?

You just need to keep all the words separate and then join them later with a space between them:
import string
def string_processing(string_list):
ret = []
for word in string_list:
ret.append(''.join(x for x in word if x not in string.punctuation))
return ' '.join(ret)
print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))
Output:
hello world
test me please

Using regex, remove every non-letter and then join with a space:
import re
def string_processing(string_list):
return ' '.join(re.sub(r'[^a-zA-Z]', '', word) for word in string_list)
print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))
Gives:
hello world
test me please

Try:
import string
def string_processing(string_list):
str1 = ""
for word in string_list:
st = ''.join(x for x in word if x not in string.punctuation)
str1 += f"{st} " #<-------- here
return str1.rstrip() #<------- here
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
using regex:
import re
li = ['hello...,', 'world!']
st = " ".join(re.compile('\w+').findall("".join(li)))

The following code could help.
import string
def string_processing(string_list):
for i,word in enumerate(string_list):
string_list[i] = word.translate(str.maketrans('', '', string.punctuation)).lower()
str1 = " ".join(string_list)
return str1
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])

We can use the re library to process the words and add a space between them
import re
string = 'HelloWorld'
print(re.sub('([A-Z])', r' \1', string))
Output:
Hello World

Related

Python how to get a word in string via specified character?

a = "I only want the $1000"
print(get_word_containing("$")
output: $1000
How would I get the whole word within a string by a character within that word to work like shown above?
Your function can be as simple as follows:
def get_word_containing(string, char):
words = [word for word in string.split() if char in word]
return words
string = "I only want the $1000"
print(get_word_containing(string, "$"))
Output:
['$1000']
I will modify #Biplob function a little to print the strings instead:
def get_word_containing(myStr, char):
for x in myStr.split():
if char in x:
print(x)
mystring = "I only want the $1000"
get_word_containing(mystring, "$")
import re
a = "I only want the $1000"
list = re.findall("[$]\w+", text)
print(list)
Above code will give you array of all words starts with $ in your string
import re
def get_word_containing(myStr, char):
list = re.findall("["+char+"]\w+", myStr)
return list;
mystring = "I only $200 want the $1000"
ouput = get_word_containing(mystring, "$")
print(ouput);
So it will give us ['$200', '$1000']

Python -Remove capitalized words from long string

I have long string (28MB) of normal sentences. I want to remove all words what are fully in capital letters (like TNT, USA, OMG).
So from sentance:
Jump over TNT in There.
I would like to get:
Jump over in There.
Is there any way, how to do it without splitting the text into list and itereate? Is it possible to use regex somehow to do is?
You can use the set of capital letters [A-Z] captured with word boundary \b:
import re
line = 'Jump over TNT in There NOW'
m = re.sub(r'\b[A-Z]+\b', '', line)
#'Jump over in There '
Use the module re,
import re
line = 'Jump over TNT in There.'
new_line = re.sub(r'[A-Z]+(?![a-z])', '', line)
print(new_line)
# Output
Jump over in There.
I would do something like this:
import string
def onlyUpper(word):
for c in word:
if not c.isupper():
return False
return True
s = "Jump over TNT in There."
for char in string.punctuation:
s = s.replace(char, ' ')
words = s.split()
good_words = []
for w in words:
if not onlyUpper(w):
good_words.append(w)
result = ""
for w in good_words:
result = result + w + " "
print result

How to preserve and reverse a string?

Write a function that accepts a string of words separated by spaces
consisting of alphabetic characters and returns a string such that
each word in the input string is reversed while the order of the words
in the input string is preserved. Capitalization does matter here. The
length of the input string must be equal to the length of the output
string i.e. there should be no trailing or leading spaces in your
output string. For example if:
input_string = “this is a sample test”
then the function should return a string such as:
"siht si a elpmas tset"
This is my code:
def preserve_and_reverse (input_str):
list = input_str.split()
print (list)
reverse_character = ""
for i in range (0, len(input_str)):
split_list = list[0:(i + 1)]
print (split_list)
for j in split_list_advance:
reverse_character = reverse_character + split_list[j]
output_str = output_str.append(reverse_character)
output = output_str.replace("", " ")
print (output)
#Main Program
input_str = input("Enter a string: ")
result = preserve_and_reverse (input_str)
print (result)
I am not getting anywhere with the code. Should I try a different approach like traverse each character and when I encounter a white-space just slice the string and then perform a reverse?
Any help would be appreciated.
Split over spaces, reverse each string through map with [::-1] then join them back with ' '.join
>>> s = 'this is a sample test'
>>>
>>> ' '.join(map(lambda s:s[::-1], s.split()))
'siht si a elpmas tset'
This is how I would have done it:
def preserve_and_reverse(input_str):
# Split the String into an Array
list_ = input_str.split(" ")
return_str = ""
# For Each String in the Array
for item in list_:
# Add Reversed String to Return String
return_str += item[::-1] + " "
# Return String without leading/trailing spaces
return return_str.strip()
# Main Program
string_input = input("Enter a string: ")
result = preserve_and_reverse(string_input.strip())
print(result)
Something like this will do (step-by-step):
input_string = "this is a sample test"
words = input_string.split()
nwords = []
for i in words:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
output_string = " ".join(nwords)
print(output_string)
Result:
siht si a elpmas tset
Step by step explanation:
You split your input text into list of string:
words = input_string.split()
You iterate over the words
for word in words):
For each word, you prepare a reversed word rword and build up the reversed word by adding up character from the old word but reversed:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
you rejoin the reversed words - but in order and print it:
output_string = " ".join(nwords)
print(output_string)
Or, more simply:
input_string = "this is a sample test"
words = input_string.split()
output_string = ""
for word in words:
for c in reversed(word):
output_string += c
output_string += " "
print(output_string)
word[::-1] reverses the order of the string variable named word which is obtained by iterating through each split word in the sentence.
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
Step by step:
>>> input_string.split()
['this', 'is', 'a', 'sample', 'test']
>>> [word[::-1] for word in input_string.split()]
['siht', 'si', 'a', 'elpmas', 'tset']
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
All of the other answers so far ignore what happens when extra spaces are between words or at either end of the input string. Please test your code to verify that is works properly. The main function provided below has a few tests that you may want to use to verify your function is working properly, and you may want to add more tests if you find that your code is not behaving correctly:
def main():
print('Running test 1 ...')
text = 'this is a sample test'
par = preserve_and_reverse(text)
assert par == 'siht si a elpmas tset'
print('Running test 2 ...')
text = 'This is a sample TEST'
par = preserve_and_reverse(text)
assert par == 'sihT si a elpmas TSET'
print('Running test 3 ...')
text = 'This string has some extra spaces'
par = preserve_and_reverse(text)
assert par == 'sihT gnirts sah emos artxe secaps'
print('Running test 4 ...')
text = ' check spaces at string ends '
par = preserve_and_reverse(text)
assert par == ' kcehc secaps ta gnirts sdne '
print('Done!')
def preserve_and_reverse(text):
return ' '.join(word[::-1] for word in text.split(' '))
if __name__ == '__main__':
main()
def sample(string):
list=[]
string1=string.split()
for i in string1:
list.append(i[::-1])
print(" ".join(list))
if __name__=="__main__":
input=input("Enter string: ")
sample(input)

Reverse each word in a string

I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar"
The code almost works. It just does not add spaces. How would you do that?
def reverseEachWord(str):
reverseWord=""
list=str.split()
for word in list:
word=word[::-1]
reverseWord=reverseWord+word+""
return reverseWord
You are on the right track. The main issue is that "" is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word).
Here is how you can do this more concisely:
>>> s='The dog ran'
>>> ' '.join(w[::-1] for w in s.split())
'ehT god nar'
def reversed_words(sequence):
return ' '.join(word[::-1] for word in sequence.split())
>>> s = "The dog ran"
>>> reversed_words(s)
... 'ehT god nar'
name=input('Enter first and last name:')
for n in name.split():
print(n[::-1],end=' ')
You can also deal with noise in the string using the re module:
>>> import re
>>> s = "The \n\tdog \t\nran"
>>> " ".join(w[::-1] for w in re.split(r"\s+", s))
'ehT god nar'
Or if you don't care:
>>> s = "The dog ran"
>>> re.sub(r"\w+", lambda w: w.group(0)[len(w.group(0))::-1], s)
'Teh god nar'
def reverse_words(sentence):
return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" ")))
Another way to go about it is by adding a space to your words reverseWord=reverseWord+word+" " and removing the space at the end of your output by using .strip()
def reverse_words(str):
reverseWord = ""
list = str.split()
for word in list:
word = word[::-1]
reverseWord = reverseWord + word + " "
return reverseWord.strip()
check out this post on how it's used
Here is a solution without using join / split :
def reverse(sentence):
answer = ''
temp = ''
for char in sentence:
if char != ' ':
temp += char
continue
rev = ''
for i in range(len(temp)):
rev += temp[len(temp)-i-1]
answer += rev + ' '
temp = ''
return answer + temp
reverse("This is a string to try")

String reverse in Python

Write a simple program that reads a line from the keyboard and outputs the same line where
every word is reversed. A word is defined as a continuous sequence of alphanumeric characters
or hyphen (‘-’). For instance, if the input is
“Can you help me!”
the output should be
“naC uoy pleh em!”
I just tryed with the following code, but there are some problem with it,
print"Enter the string:"
str1=raw_input()
print (' '.join((str1[::-1]).split(' ')[::-2]))
It prints "naC uoy pleh !em", just look the exclamation(!), it is the problem here. Anybody can help me???
The easiest is probably to use the re module to split the string:
import re
pattern = re.compile('(\W)')
string = raw_input('Enter the string: ')
print ''.join(x[::-1] for x in pattern.split(string))
When run, you get:
Enter the string: Can you help me!
naC uoy pleh em!
You could use re.sub() to find each word and reverse it:
In [8]: import re
In [9]: s = "Can you help me!"
In [10]: re.sub(r'[-\w]+', lambda w:w.group()[::-1], s)
Out[10]: 'naC uoy pleh em!'
My answer, more verbose though. It handles more than one punctuation mark at the end as well as punctuation marks within the sentence.
import string
import re
valid_punctuation = string.punctuation.replace('-', '')
word_pattern = re.compile(r'([\w|-]+)([' + valid_punctuation + ']*)$')
# reverses word. ignores punctuation at the end.
# assumes a single word (i.e. no spaces)
def word_reverse(w):
m = re.match(word_pattern, w)
return ''.join(reversed(m.groups(1)[0])) + m.groups(1)[1]
def sentence_reverse(s):
return ' '.join([word_reverse(w) for w in re.split(r'\s+', s)])
str1 = raw_input('Enter the sentence: ')
print sentence_reverse(str1)
Simple solution without using re module:
print 'Enter the string:'
string = raw_input()
line = word = ''
for char in string:
if char.isalnum() or char == '-':
word = char + word
else:
if word:
line += word
word = ''
line += char
print line + word
you can do this.
print"Enter the string:"
str1=raw_input()
print( ' '.join(str1[::-1].split(' ')[::-1]) )
or then, this
print(' '.join([w[::-1] for w in a.split(' ') ]))

Categories