How to add new line after number of word - python

i find a code to seperate line, but it cut hafl of word "A very very long str" \n "ing from user input". so i want to ask how to keep the original word. its mean add \n after a number of word?
# inp = "A very very long string from user input"
# new_input = ""
# for i, letter in enumerate(inp):
# if i % 20 == 0:
# new_input += '\n'
# new_input += letter
#
# # this is just because at the beginning too a `\n` character gets added
# new_input = new_input[1:]
# print(new_input)

Using a simple loop on a list of the words:
inp = "A very very long string from user input"
start = 0
N = 3
l = inp.split()
for stop in range(N, len(l)+N, N):
print(' '.join(l[start:stop]))
start = stop
output:
A very very
long string from
user input
update: splitting with a max number of characters
If you need this, don't reinvent the wheel, use textwrap.wrap:
inp = "A very very long string from user input"
from textwrap import wrap
print('\n'.join(wrap(inp, width=20)))
output:
A very very long
string from user
input

I see that there is already an accepted answer, but I'm not sure that it completely answers the original question. The accepted answer will only split the string provided into lines with 3 words each. However, what I understand the question to be is for the string to be split into lines of a certain length (20 being the length provided). This function should work:
def split_str_into_lines(input_str: str, line_length: int):
words = input_str.split(" ")
line_count = 0
split_input = ""
for word in words:
line_count += 1
line_count += len(word)
if line_count > line_length:
split_input += "\n"
line_count = len(word) + 1
split_input += word
split_input += " "
else:
split_input += word
split_input += " "
return split_input
inp = "A very very long string from user input"
length = 20
new_input = split_str_into_lines(inp,length)
print(new_input)
new_input
Giving result:
"""
A very very long
string from user
input
"""
or
'A very very long \nstring from user \ninput '

Try using str.split() 1 and give it space as a delimiter:
words = inp.split(' ')
That should return a list of words

Related

Python Count Characters

Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's if the number of times the characters appears is not exactly 1.
Ex: If the input is:
n Monday
the output is:
1 n
Ex: If the input is:
z Today is Monday
the output is:
0 z's
Ex: If the input is:
n It's a sunny day
the output is:
2 n's
Case matters. n is different than N.
Ex: If the input is:
n Nobody
the output is:
0 n's
This is what I have so far:
user_string=input(str())
character=user_string[0]
phrase=user_string[1]
count=0
for i in phrase:
if i == character:
count = count+1
if count!= 1:
print(str(count) + " " + character + "'s")
else:
print(str(count) + " " + character)
This works great for the phrases that have 0 characters matching. But its not counting the ones that should match.
user_string=input(str())
character=user_string[0]
phrase=user_string[1:]
count=0
for i in phrase:
if i == character:
count = count+1
if count != 1:
print(str(count) + " " + character + "'s")
else:
print(str(count) + " " + character)
We will take the user's input, with the assumption that the first letter is the one that you are counting, and find that character with user_string.split()[0]. We will then take all the other words from the user's input (with user_string.split()[1:]), join them with ''.join and then explode them into a list of letters with [*]. We will return a list of "hits" for the character we are looking for. The length of that list will be the number of "hits".
user_string=input()
numOfLetters = [letter for letter in [*''.join(user_string.split()[1:])]
if user_string[0]==letter]
print(f'Number of {user_string[0]} is: {len(numOfLetters)}')
t This is a test # Input
Number of t is: 2 # Output
h Another test for comparison # Input
Number of h is: 1 # Output
Suggest just using str.count.
user_string = input()
character, phrase = user_string[0], user_string[1:]
count = phrase.count(character)
print(f"{count} {character}" + "'s" if count != 1 else '')
user_phrase=input()
letter=user_phrase[0]
if letter in user_phrase:
if user_phrase.count(letter)>2:
print (f'{user_phrase.count(letter)-1} {letter}\'s')
elif user_phrase.count(letter)==1:
print(f'0 {letter}\'s')
else:
print(f'{user_phrase.count(letter)-1} {letter}')
letter_and_phrase = str(input())
number_times_char_appears = 0
begin_letter = letter_and_phrase[0]
split_phrase = letter_and_phrase[1:].strip(' ')
for letter in split_phrase:
if letter in begin_letter:
number_times_char_appears += 1
if number_times_char_appears > 1:
print(f"{number_times_char_appears} {begin_letter}'s")
elif number_times_char_appears == 0:
print(f"{number_times_char_appears} {begin_letter}'s")
else:
print(f"{number_times_char_appears} {begin_letter}")

How do I choose 2 or more letters in a word?

Basically my plan was to return text with random-sized letters in words i.e. "upper" or "lower". The script is working, though it seems raw (I am a Beginner and I'd appreciate some corrections from You).
The problem is:
It is not consistent. With that said, it can print word 'about' even if it should be 'About' or something similar.
I want to be sure that the maximum of UPPER or lower letters in a row do not exceed 3 letters. and I don't know how to do it.
Thank you in advance.
#!/usr/bin/env python3
import random
message = input()
stop = ''
def mocking(message):
result = ''
for word in message:
for letter in word:
word = random.choice(random.choice(letter.upper()) + random.choice(letter.lower()))
result += word
return result
while stop != 'n':
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
You need to split the input into words, decide how many positions inside the word you want to change (minimum 3 or less if the word is shorter).
Then generate 3 unique positions inside the word (via random.sample) to change, check if upper then make lower else make upper. Add to resultlist and join words back together.
import random
message = "Some text to randomize"
def mocking(message):
result = []
for word in message.split():
len_word = len(word)
# get max 3 random positions
p = random.sample(range(len_word),k = min(len_word,3))
for position in p:
l = word[position]
if l.isupper():
word = word[:position] + l.lower() + word[position+1:]
else:
word = word[:position] + l.upper() + word[position+1:]
result.append(word)
return ' '.join(result)
while True:
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
See Understanding slice notation for slicing
At most 3 modifications? I would go with something like this.
def mocking(message):
result = ''
randomCount = 0
for word in message:
for letter in word:
newLetter = random.choice( letter.upper() + letter.lower() )
if randomCount < 3 and newLetter != letter:
randomCount += 1
result += newLetter
else:
result += letter
randomCount = 0
return result
If the random choice has modified the letter then count it.

how to exchange the middle letter and last letter switched?

Ask the user for the input of a word with a minimum of 3 characters. Take that word and exchange the MIDDLE letter with the LAST letter of the word.
If the word is an even number of characters long, take the letter to the right of middle (IE if a word is 6 letters long, you want the 4th character: “switch” is 6 characters and we’d want the ‘t’ as our middle character.
Output to the user their newly rearranged word.
*additional difficulty perform a check that the word is at LEAST 3 letters and display a message that it’s not long enough if something shorter than 3 characters is displayed.strong text
can you guys help me with this?
My code so far:
word=input('Please enter a word with a minimum of 3 characters')
word_length=len(word)
word_middle_index = int(word_length//2)
print('The letter in the middle of the word "'+word+'" is:
word[word_middle_index])
this is how much I've done
this function will complete the task for you:
def switch_mid_and_last(word):
if len(word) < 3:
return("too short word")
else:
mid_letter = len(word)//2
new_word = word[:mid_letter] + word[-1] + word[mid_letter+1:-1] + word[mid_letter]
return(new_word)
the outputs for the next inputs are:
print(switch_mid_and_last("ab"))
>>> too short word
print(switch_mid_and_last("abc"))
>>> acb
print(switch_mid_and_last("abcd"))
>>> abdc
print(switch_mid_and_last("abcde"))
>>> abedc
print(switch_mid_and_last("abcdef"))
>>> abcfed
I've done it so that you can learn how to approach such a problem :
I'd recommend looking into a couple things online :
len function
% operator
[:] operator
For instance :
n % 2 == 0 is True when is even.
"abcd"[1:4] returns "bcd"
word = input("Enter A Word: ")
if len(word) < 3:
print("The word length as to be more than 3 characters")
else:
newWord = ""
middleLetterIndex = 0
lastLetterIndex = len(word) - 1
if len(word) % 2 == 0: # even
middleLetterIndex = int(len(word) / 2) + 1
else:
middleLetterIndex = int(len(word) / 2)
middleLetter = word[middleLetterIndex]
lastLetter = word[lastLetterIndex]
newWord = word[:middleLetterIndex]
newWord += lastLetter
newWord += word[middleLetterIndex+1:lastLetterIndex]
newWord += middleLetter
print(newWord)
Hope this helps you!
For making this easier to grasp, I haven't used any functions, classes, encapsulations or DRY principle here. Since you wanted to show helpful messages in each case, I have also added them.
while True:
word = input("Put a word with at least 3 letters: ")
# check if the word has at least 3 letters
if len(word) < 3:
print("Word needs to be at least 3 letters long!!")
break
# check odd
if not len(word) % 2 == 0:
print("Word length is odd!!!")
# make a list of letters
word_lst = [letter for letter in word]
# mid index
mid_ix = (len(word) - 1) // 2
# last index
last_ix = len(word) - 1
# swap middle and last character
word_lst[mid_ix], word_lst[last_ix] = word_lst[last_ix], word_lst[mid_ix]
# make the list into a string again
word = "".join(word_lst)
print(word)
break
# check even
else:
print("Word length is even!!!")
# make a list of letters
word_lst = [letter for letter in word]
# mid index
mid_ix = (len(word) - 1) // 2 + 1
# last index
last_ix = len(word) - 1
# swap middle and last character
word_lst[mid_ix], word_lst[last_ix] = word_lst[last_ix], word_lst[mid_ix]
# make the list into a string again
word = "".join(word_lst)
print(word)
break

Issues when grabbing words of a specific length from a txt file in python

The main confusion I am having with my code is that I am aiming to find all the words in the dictionary.txt of a particular length containing just a single vowel (defined as a, e, i, o and u) that does not have a particular letter in it. However, it does not work correctly. For example, if I am looking for all the words of length 9 containing just a single vowel that does not have letter ‘t’ in it, the
program below tells me “There are no words that fit this criteria”. But there should be two
words in the file satisfying the above criteria: “lynchings”, and “lynchpins”.
My dictionary is located at https://filebin.net/96k7kso4i6nxcd2n/dictionary.txt?t=x9ujn62v
def onevowel(file):
length = int(input("Please enter the word length you are looking for: "))
letter = input("Please enter the letter you'd like to exclude: ")
wordnum = 0
for word in file:
word = word.strip()
if len(word) == length:
count = 0
for char in word:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):
count += 1
if count == 1:
flag = 1
word_str = ""
for char in word:
if char == letter:
flag = 0
else:
word_str += char
if flag == 1:
print (word_str)
wordnum += 1
if wordnum == 0:
print ("There are no words that fit this criteria.")
if __name__ == "__main__":
my_file = open("dictionary.txt","r")
onevowel(my_file)
my_file.close()
Replace char=='a' and char=='e' and char=='i' and char=='o' and char=='u' (which is never true) with char in "aeoui".
Because you want only a single vowel, use the or condition rather than and in this line:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):

How to compare sentence character by character in python?

I want to write a code to count number of words in a given sentence by using character comparison and below is the code I have written as I am not allowed to use some fancy utilities like split(), etc. So, could you please guide me where am I making mistakes' I am a novice in python and currently trying to fiigure out how to do charactery by character comparison so as to find out simple counts of words, lines, strings withous using built in utitilites. So, kindly guide me about it.
Input Sentence : I am XYZ
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
while(Input_Sentence[i] != "\n"):
if(Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
print ('Number of Words in a given sentence is :' +str(count))
At first I wouldn't use a while loop in this context. Why not using a for loop?
for char in Input_sentence:
With this you iterate over every letter.
Then you can use the rest of you code and check:
if char == ' ':
# initialize the counter
word_count = 0
last_space_index = 0
# loop through each character in the sentence (assuming Input_Sentence is a string)
for i, x in enumerate(Input_Sentence): # enumerate to get the index of the character
# if a space is found (or newline character for end of sentence)
if x in (' ', '\n'):
word_count += 1 # increment the counter
last_space_index = i # set the index of the last space found
if len(Input_Sentence) > (last_space_index + 1): # check if we are at the end of the sentence (this is in case the word does not end with a newline character or a space)
word_count += 1
# print the total number of words
print 'Number of words:', word_count
The following will avoid errors if there's an space at the beginning or the end of the sentence.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
sentence_length = len(Input_Sentence)
for i in range(sentence_length):
if Input_Sentence[i] == " ":
if i not in (0, sentence_length - 1):
count += 1
count += 1
print "There are %s words in the sentence \"%s\"." % (count, Input_Sentence)
You may use try-except syntax.
In your code you used while(Input_Sentence[i] != "\n") to find when the sentence comes to an end. If you just print the output at every step before i+ = 1 like this:
...
while(Input_Sentence[i] != "\n"):
...
print i,Input_Sentence[i]
i+=1
else:
print i,Input_Sentence[i],'*'
i+=1
...
you can see for yourself that the output is something like this:
Enter your sentence: Python is good
Python is good
0 P *
1 y *
2 t *
3 h *
4 o *
5 n *
6
7 i *
8 s *
9
10 g *
11 o *
12 o *
13 d *
Traceback (most recent call last):
File "prog8.py", line 19, in <module>
while(Input_Sentence[i] != "\n"):
IndexError: string index out of range
which means that the code that you have written works fine upto the length of the input sentence. After that when i is increased by 1 and it is demanded of the code to check if Input_Sentence[i] == "\n" it gives IndexError. This problem can be overcome by using exception handling tools of Python. Which leaves the option to neglect the block inside try if it is an exception and execute the block within except instead.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
try:
while (Input_Sentence[i] != "\n"):
if (Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
except:
count = count+1
print ('Number of Words in a given sentence is :' +str(count))

Categories

Resources