I am trying to build a function that will take a string and print every other letter of the string, but it has to be without the spaces.
For example:
def PrintString(string1):
for i in range(0, len(string1)):
if i%2==0:
print(string1[i], sep="")
PrintString('My Name is Sumit')
It shows the output:
M
a
e
i
u
i
But I don't want the spaces. Any help would be appreciated.
Use stepsize string1[::2] to iterate over every 2nd character from string and ignore if it is " "
def PrintString(string1):
print("".join([i for i in string1[::2] if i!=" "]))
PrintString('My Name is Sumit')
Remove all the spaces before you do the loop.
And there's no need to test i%2 in the loop. Use a slice that returns every other character.
def PrintString(string1):
string1 = string1.replace(' ', '')
print(string1[::2])
Replace all the spaces and get every other letter
def PrintString(string1):
return print(string1.replace(" ", "") [::2])
PrintString('My Name is Sumit')
It depends if you want to first remove the spaces and then pick every second letter or take every second letter and print it, unless it is a space:
s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
Prints:
MnmiSmi
Maeiumt
You could alway create a quick function for it where you just simply replace the spaces with an empty string instead.
Example
def remove(string):
return string.replace(" ", "")
There's a lot of different approaches to this problem. This thread explains it pretty well in my opinion: https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/
Related
odd_integer = int(input())
integer_list = []
for i in range(0,odd_integer):
rand_int = int(input())
integer_list.append(rand_int)
integer_list.reverse()
middle_value = int(len(integer_list)/2)
print(f"{integer_list[0:middle_value]}-[{integer_list[middle_value]}]-{integer_list[middle_value+1:]}")
answer is [2, 5]-[4]-[3, 1]
but it should be [2,5]-[4]-[3,1]
You can use replace() in your string
For example:
your_string.replace(", ", ",")
Where according to your question only the ", " (comma followed by space) is replaced by "," (comma).
This is due to your print statement. What you can do is first assign it to a variable, replace the spaces and then print it.
The replace and print can be combined since replace returns the new string.
So basically:
output = f"{integer_list[0:middle_value]}-[{integer_list[middle_value]}]-{integer_list[middle_value+1:]}"
print(output.replace(" ", "")
the space after the coma is the standard representation when you print an array.
try to simply print([1,2]) you will have the same result.
if you really need no space you have to rewrite the way to display the array.
for example like this :
print(f"{','.join(map(str,integer_list[0:middle_value]))}-[{integer_list[middle_value]}]-{','.join(map(str,integer_list[middle_value+1:]))}")
join function will merge into a string with comma separated as noted, the map function will cast the int into str.
remove multiple space python
import re
re.sub(' +', ' ', 'hello hi there')
'hello hi there'
remove after and before space python
st = " a "
strip(st)
#Output : "a"
What's the difference between:
stringline = string.split(' ')
int_part = int(stringline[1])
string_part = stringline[0]
and
string_part = string[:-1]
int_part = int(string[-1:])
where stringline = "HACK 2" ?
I believed both were the same but when I try to use them to print list elements using itertools.permutations(), I get different results.
string[:-1] just removes the very last character and gives you "HACK " (notice the space) whereas string.split(" ")[0] gives you the element "HACK" (notice no space).
That's because split also removes the space from the original string and returns a list of ["HACK", "2"], whereas string[:-1] just stop return characters at "2".
It is simply because string_part = string[:-1] gives 'HACK ' with space, so itertools.permutations() will count the space in the iterable as well.
i need to make a program that will capitalize the first word in a sentence and i want to be sure that all the special characters that are used to end a sentence can be used.
i can not import anything! this is for a class and i just want some examples to do this.
i have tried to use if to look in the list to see if it finds the matching character and do the correct split operatrion...
this is the function i have now... i know its not good at all as it just returns the original string...
def getSplit(userString):
userStringList = []
if "? " in userString:
userStringList=userString.split("? ")
elif "! " in userStringList:
userStringList = userString.split("! ")
elif ". " in userStringList:
userStringList = userString.split(". ")
else:
userStringList = userString
return userStringList
i want to be able to input something like this is a test. this is a test? this is definitely a test!
and get [this is a test.', 'this is a test?', 'this is definitely a test!']
and the this is going to send the list of sentences to another function to make the the first letter capitalized for each sentence.
this is an old homework assignment that i could only make it use one special character to separate the string into a list. buti want to user to be able to put in more then just one kind of sentence...
This may hep. use str.replace to replace special chars with space and the use str.split
Ex:
def getSplit(userString):
return userString.replace("!", " ").replace("?", " ").replace(".", " ").split()
print(map(lambda x:x.capitalize, getSplit("sdfsdf! sdfsdfdf? sdfsfdsf.sdfsdfsd!fdfgdfg?dsfdsfgf")))
Normally, you could use re.split(), but since you cannot import anything, the best option would be just to do a for loop. Here it is:
def getSplit(user_input):
n = len(user_input)
sentences =[]
previdx = 0
for i in range(n - 1):
if(user_input[i:i+2] in ['. ', '! ', '? ']):
sentences.append(user_input[previdx:i+2].capitalize())
previdx = i + 2
sentences.append(user_input[previdx:n].capitalize())
return "".join(sentences)
I would split the string at each white space. Then scan the list for words that contain the special character. If any is present, the next word is capitalised. Join the list back at the end. Of course, this assumes that there are no more than two consecutive spaces between words.
def capitalise(text):
words = text.split()
new_words = [words[0].capitalize()]
i = 1
while i < len(words) - 1:
new_words.append(words[i])
if "." in words[i] or "!" in words[i] or "?" in words[i]:
i += 1
new_words.append(words[i].capitalize())
i += 1
return " ".join(new_words)
If you can use the re module which is available by default in python, this is how you could do it:
import re
a = 'test this. and that, and maybe something else?even without space. or with multiple.\nor line breaks.'
print(re.sub(r'[.!?]\s*\w', lambda x: x.group(0).upper(), a))
Would lead to:
test this. And that, and maybe something else?Even without space. Or with multiple.\nOr line breaks.
Write programs that read a line of input as a string and print every second letter of the string in Python?
So far I have written:
string=input('Enter String: ')
for char in range(0,len(string),2):
print(len(char))
if i input a string: qwerty
it should print "qet"
You need to keep it much simpler than this. If you enter a word and are looking to slice it at a specific point, use slicing.
Your criteria: qwerty it should print "qet"
So, you are looking to print every second letter:
>>> a = "querty"
>>> a[::2]
'qet'
Slicing works like this:
[from start: from end: step]
So, in your case, you are looking to simply print every second, so you want to make use of your step. So, simply slice leaving the start and end empty, since you want to position yourself at the beginning of the string and then simply go every second. This is the reasoning behind using [::2]
Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".
Code below may be able to answer your question.
sentence = input("\nPlease enter a string : ")
print("Every second letter of the string " + sentence + " is ", end="")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i] + " ", end="")
So I've been learning Python for some months now and was wondering how I would go about writing a function that will count the number of times a word occurs in a sentence. I would appreciate if someone could please give me a step-by-step method for doing this.
Quick answer:
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
'some string.split() will split the string on whitespace (spaces, tabs and linefeeds) into a list of word-ish things. Then ['some', 'string'].count(item) returns the number of times item occurs in the list.
That doesn't handle removing punctuation. You could do that using string.maketrans and str.translate.
# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))
def count_occurrences(word, sentence):
return sentence.lower().translate(table, delete).split().count(word)
The key here is that we've constructed the string delete so that it contains all the ascii characters except letters, numbers and spaces. Then str.translate in this case takes a translation table that doesn't change the string, but also a string of chars to strip out.
wilberforce has the quick, correct answer, and I'll give the long winded 'how to get to that conclusion' answer.
First, here are some tools to get you started, and some questions you need to ask yourself.
You need to read the section on Sequence Types, in the python docs, because it is your best friend for solving this problem. Seriously, read it. Once you have read that, you should have some ideas. For example you can take a long string and break it up using the split() function. To be explicit:
mystring = "This sentence is a simple sentence."
result = mystring.split()
print result
print "The total number of words is: " + str(len(result))
print "The word 'sentence' occurs: " + str(result.count("sentence"))
Takes the input string and splits it on any whitespace, and will give you:
["This", "sentence", "is", "a", "simple", "sentence."]
The total number of words is 6
The word 'sentence' occurs: 1
Now note here that you do have the period still at the end of the second 'sentence'. This is a problem because 'sentence' is not the same as 'sentence.'. If you are going to go over your list and count words, you need to make sure that the strings are identical. You may need to find and remove some punctuation.
A naieve approach to this might be:
no_period_string = mystring.replace(".", " ")
print no_period_string
To get me a period-less sentence:
"This sentence is a simple sentence"
You also need to decide if your input going to be just a single sentence, or maybe a paragraph of text. If you have many sentences in your input, you might want to find a way to break them up into individual sentences, and find the periods (or question marks, or exclamation marks, or other punctuation that ends a sentence). Once you find out where in the string the 'sentence terminator' is you could maybe split up the string at that point, or something like that.
You should give this a try yourself - hopefully I've peppered in enough hints to get you to look at some specific functions in the documentation.
Simplest way:
def count_occurrences(word, sentence):
return sentence.count(word)
text=input("Enter your sentence:")
print("'the' appears", text.count("the"),"times")
simplest way to do it
Problem with using count() method is that it not always gives the correct number of occurrence when there is overlapping, for example
print('banana'.count('ana'))
output
1
but 'ana' occurs twice in 'banana'
To solve this issue, i used
def total_occurrence(string,word):
count = 0
tempsting = string
while(word in tempsting):
count +=1
tempsting = tempsting[tempsting.index(word)+1:]
return count
You can do it like this:
def countWord(word):
numWord = 0
for i in range(1, len(word)-1):
if word[i-1:i+3] == 'word':
numWord += 1
print 'Number of times "word" occurs is:', numWord
then calling the string:
countWord('wordetcetcetcetcetcetcetcword')
will return: Number of times "word" occurs is: 2
def check_Search_WordCount(mySearchStr, mySentence):
len_mySentence = len(mySentence)
len_Sentence_without_Find_Word = len(mySentence.replace(mySearchStr,""))
len_Remaining_Sentence = len_mySentence - len_Sentence_without_Find_Word
count = len_Remaining_Sentence/len(mySearchStr)
return (int(count))
I assume that you just know about python string and for loop.
def count_occurences(s,word):
count = 0
for i in range(len(s)):
if s[i:i+len(word)] == word:
count += 1
return count
mystring = "This sentence is a simple sentence."
myword = "sentence"
print(count_occurences(mystring,myword))
explanation:
s[i:i+len(word)]: slicing the string s to extract a word having the same length with the word (argument)
count += 1 : increase the counter whenever matched.