How to capitalize the first and last letter of a string? - python

So it's not a very difficult problem and I've been trying to do it. Here is my sample code:
import sys
for s in sys.stdin:
s = s[0:1].upper() + s[1:len(s)-1] + s[len(s)-1:len(s)].upper()
print(s)
This code only capitalizes the first letter and not the last letter as well. Any tips?

You are operating on lines, not words, since iterating over sys.stdin will give you strings that consist of each line of text that you input. So your logic won't be capitalizing individual words.
There is nothing wrong with your logic for capitalizing the last character of a string. The reason that you are not seeming to capitalize the end of the line is that there's an EOL character at the end of the line. The capitalization of EOL is EOL, so nothing is changed.
If you call strip() on the input line before you process it, you'll see the last character capitalized:
import sys
for s in sys.stdin:
s = s.strip()
s = s[0:1].upper() + s[1:len(s)-1] + s[len(s)-1:len(s)].upper()
print(s)
#Calculuswhiz's answer shows you how to deal with capitalizing each word in your input.

You first have to split the line of stdin, then you can operate on each word using a map function. Without splitting, the stdin is only read line by line in the for loop.
#!/usr/bin/python
import sys
def capitalize(t):
# Don't want to double print single character
if len(t) is 1:
return t.upper()
else:
return t[0].upper() + t[1:-1] + t[-1].upper()
for s in sys.stdin:
splitLine = s.split()
l = map(capitalize, splitLine)
print(' '.join(l))
Try it online!

You could just use the capitalize method for str which will do exactly what you need, and then uppercase the last letter individually, something like:
my_string = my_string.capitalize()
my_string = my_string[:-1] + my_string[-1].upper()

Related

Build a long string from words in a For Loop

I would like to form a long sentence using a for loop in python.
I have data that came from sys.stdin and i would like to form a long sentence from the words that came from stdin.
For example,assume the words that cam from sys.stdin were
hello
to
all
developers
My current program reads as:
word = ''
for k in sys.stdin:
sentence = word + ',' + k
print(sentence)
I have also tried this approach:
for k in sys.stdin:
word = ''
sentence = word + ',' + k
print(sentence)
All the above codes gives me the output;
,hello
,to
,all
,developers
But I need an output as;
hello,to,all,developers
Please Note; I NEED THE VARIABLE 'sentence' INSIDE THE LOOP BECAUSE IT WILL BE RE-USED IN THE LOOP LATER.
Any help please? Thank you for your input.
Not as familiar with for loops in python, but maybe you could try putting the "print(sentence" outside of the for loop, because print() is always going to make a new line
Try this
word = ''
for k in sys.stdin:
word = word + ',' + k
print(word)
You need to modify word, you were creating another variable each time inside the loop
sentence = ','.join(k for k in sys.stdin)
Try this
import sys
sentence = []
for k in sys.stdin:
if "\n" in k: # sys.stdin input contains newlines, remove those first
sentence.append(k[:-1]) # removes the \n (newline literal) before adding to sentence list
else:
sentence.append(k)
print(",".join(sentence)) # converts the list of words into one long string separated with commas
My approach to this contains one key step that other answers are missing, which is removing the newline "\n" from sys.stdin input.
When you try this code snippet, you'll get your output in one line.
You can use your approach
word = ''
for k in sys.stdin:
sentence = word + ',' + k
print(sentence)
just add
sentence = sentence.replace('\n','')[1:]
after the loop

Checking characters in an input file line, and returning if they contain only valid characters

So I want to run a program that will read in a file line by line, and will then print out either Valid or Invalid based on what each line contains.
For this example, I am saying that the input file line can contain ABCabc or a space. If the line only contains these things, the word Valid should be printed. If it is just white space, or contains any other characters or letters, it should print out “Invalid”.
This is what I have come up with:
I can’t seem to get it to ever print out “Valid”
Can you tell why? Thanks!
input = sys.argv[1]
input = open(input,"r")
correctInput = ‘ABCabc ‘
line1 = input.readline()
while line1 != "":
if all(char in correctInput for char in line1):
print “Valid”
line2 = input.readline()
else:
print “Invalid”
line2 = input.readline()
line1 = line2
If you print out the value of line1 before your if else statement, you'll see it has a newline character in it. (The \n character.) This is the character that gets added to the end of each line whenever you hit the enter key on the keyboard, and you need to either discard the newline characters or include them as valid input.
To include it as valid input
Change correctInput = 'ABCabc '
to
correctInput = 'ABCabc \n'.
Or to discard the newline characters change
if all(char in correctInput for char in line1):
to
if all(char in correctInput for char in line1.replace('\n', '')):
Either method will work.
Bytheway, input is a function in Python. Although you're allowed to use it as a variable name, doing so will prevent you from using the input function in your program. Because of this, it is considered bad practice to use any of the built in function names as your variable names.
RegEx Solution
Just for fun, I came up with the following solution which solves your problem using regular expressions.
import re
with open(sys.argv[1]) as fh:
valid_lines = re.findall('^[ABCabc ]+\n', fh.read())
This finds any valid lines using the pattern '^[ABCabc ]+\n'. What does this regular expression pattern do?
The ^ symbol signifies the start of a line
Then comes the [ABCabc ]. When brackets are used, only characters inside of those brackets will be allowed.
The + after the brackets means that those characters that where in brackets must be found 1 or more times.
And lastly we make sure the valid characters we found are followed by a newline character (\n). This ensures we checked the complete line for valid characters.
Its because readline doesn't remove '\n' from end of the line. You could ignore that problem by splitting whole file content in lines and than validate them one by one.
import sys
file_name = sys.argv[1]
file = open(file_name ,"r")
correctInput = 'ABCabc '
lines = file.read().splitlines()
for line1 in lines:
if all(char in correctInput for char in line1):
print 'Valid'
else:
print 'Invalid'

Print the string, if string in the line ends with specific characters

How do I print every string that ends on 'je' in a line
For example :
for line in sys.stdin:
for string in line:
if string ends with 'je':
print string
And only if the string ends with '....je' , so no 'je' included. And if the string ends with '....je?' or '....je.' remove '? , . ' . Then it should print the string. Help would be appreciated.
Assuming that your string name dosent allow '?,.' at all, it should work.
for line in sys.stdin:
for string in line:
string = string.strip('.,?')
if string.endswith('je'):
print(string)
There are two problems in your code. for string in line: will go through every single character, not through every word. By the way, you should not name your variable string. for word in line.split(): will do what you expect.
Also, if string ends with 'je': should be if word.endswith('je'):. If you don't want to match the exact word "je", you can change that to if word.endswith('je') and word != "je":.
Final code, including the removal of ! and ?:
f = open("a.txt", "r")
for line in f:
for word in line.split():
word = word.rstrip("!?")
if word.endswith('je') and word != "je":
print(word)
Note that if a word ends with several ? or !, they will all get removed.

How do I output the acronym on one line

I am following the hands-on python tutorials from Loyola university and for one exercise I am supposed to get a phrase from the user, capatalize the first letter of each word and print the acronym on one line.
I have figured out how to print the acronym but I can't figure out how to print all the letters on one line.
letters = []
line = input('?:')
letters.append(line)
for l in line.split():
print(l[0].upper())
Pass end='' to your print function to suppress the newline character, viz:
for l in line.split():
print(l[0].upper(), end='')
print()
Your question would be better if you shared the code you are using so far, I'm just guessing that you have saved the capital letters into a list.
You want the string method .join(), which takes a string separator before the . and then joins a list of items with that string separator between them. For an acronym you'd want empty quotes
e.g.
l = ['A','A','R','P']
acronym = ''.join(l)
print(acronym)
You could make a string variable at the beginning string = "".
Then instead of doing print(l[0].upper()) just append to the string string += #yourstuff
Lastly, print(string)

Is there a specific way to input characters at the beginning of a new line?

Current I am trying to implement a way to input ">" at the beginning of each separate line in a string.
An example would be:
String:
"Hello how are you!
Python is cool!"
Now that's all one big string, with a line break. But is there a function to establish when and where the line break is? For as I stated above, I'd like to incorporate a ">" at the beginning of each new line. Like so:
String:
">Hello how are you!
>Python is cool!"
Note: The string isn't permanently set, so that's why I am having to work around this.
Hopefully that makes sense, and thanks for your help!
Just split the lines and concat:
lines = """Hello how are you!
Python is cool!"""
for line in lines.splitlines():
if line:
print(">" + line)
else:
print(line)
>Hello how are you!
> Python is cool!
To get a new string and keep the newlines set keepends=True:
new_s = "".join([">{}".format(line) if line.strip() else line
for line in lines.splitlines(True)])
print(new_s)
>Hello how are you!
> Python is cool!
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.
Use a regular expression to find groups of non-newline characters and insert a > character before:
new_string = re.sub(r'[^\n]+', '>\g<0>', old_string) # be sure to import re
This should work exactly as print except for what you ask:
def newprint(*args, **kwargs):
to_print = " ".join([str(a) for a in args])
print(">", "\n> ".join(to_print.splitlines()), **kwargs)

Categories

Resources