Capitalize a string - python

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
I would like to be able to do all string lengths as well.

>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'

#saua is right, and
s = s[:1].upper() + s[1:]
will work for any string.

What about your_string.title()?
e.g. "banana".title() -> Banana

s = s[0].upper() + s[1:]
This should work with every string, except for the empty string (when s="").

this actually gives you a capitalized word, instead of just capitalizing the first letter
cApItAlIzE -> Capitalize
def capitalize(str):
return str[:1].upper() + str[1:].lower().......

for capitalize first word;
a="asimpletest"
print a.capitalize()
for make all the string uppercase use the following tip;
print a.upper()
this is the easy one i think.

You can use the str.capitalize() function to do that
In [1]: x = "hello"
In [2]: x.capitalize()
Out[2]: 'Hello'
Hope it helps.

Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions
Below code capitializes first letter with space as a separtor
s="gf12 23sadasd"
print( string.capwords(s, ' ') )
Gf12 23sadasd

str = str[:].upper()
this is the easiest way to do it in my opinion

Related

capitalizing the first letter in a text after split

Is there an easy way to capitalize the first letter of each word after "-" in a string and leave the rest of string intact?
x="hi there-hello world from Python - stackoverflow"
expected output is
x="Hi there-Hello world from Python - Stackoverflow"
what I tried is :
"-".join([i.title() for i in x.split("-")]) #this capitalize the first letter in each word; what I want is only the first word after split
Note: "-" isn't always surrounded by spaces
You can do this with a regular expression:
import re
x = "hi there-hello world from Python - stackoverflow"
y = re.sub(r'(^|-\s*)(\w)', lambda m: m.group(1) + m.group(2).upper(), x)
print(y)
try this:
"-".join([i.capitalize() for i in x.split("-")])
Basically what #Milad Barazandeh did but another way to do it
answer = "-".join([i[0].upper() + i[1:] for i in x.split("-")])

Converting specific letters to uppercase or lowercase in python

So to return a copy of a string converted to lowercase or uppercase one obviously uses the lower() or upper().
But how does one go about making a copy of a string with specific letters converted to upper or lowercase.
For example how would i convert 'test' into 'TesT'
this is honestly baffling me so help is greatly appreciated
got it, thanks for the help Cyber and Matt!
If you're just looking to replace specific letters:
>>> s = "test"
>>> s.replace("t", "T")
'TesT'
There is one obvious solution, slice the string and upper the parts you want:
test = 'test'
test = test[0].upper() + test[1:-1] + test[-1].upper()
import re
input = 'test'
change_to_upper = 't'
input = re.sub(change_to_upper, change_to_upper.upper(), input)
This uses the regular expression engine to say find anything that matches change_to_upper and replace it with the the upper case version.
You could use the str.translate() method:
import string
# Letters that should be upper-cased
letters = "tzqryp"
table = string.maketrans(letters, letters.upper())
word = "test"
print word.translate(table)
As a general way to replace all of a letter with something else
>>> swaps = {'t':'T', 'd':'D'}
>>> ''.join(swaps.get(i,i) for i in 'dictionary')
'DicTionary'
I would use translate().
For python2:
>>> from string import maketrans
>>> "test".translate(maketrans("bfty", "BFTY"))
'TesT'
And for python3:
>>> "test".translate(str.maketrans("bfty", "BFTY"))
'TesT'
Python3 can do:
def myfunc(str):
if len(str)>3:
return str[:3].capitalize() + str[3:].capitalize()
else:
return 'Word is too short!!'
The simplest solution:
>>> letters = "abcdefghijklmnop"
>>> trantab = str.maketrans(letters, letters.upper())
>>> print("test string".translate(trantab))
tEst strING
Simply
chars_to_lower = "MTW"
"".join([char.lower() if char in chars_to_lower else char for char in item]

String function to strip the last comma

Input
str = 'test1,test2,test3,'
Ouput
str = 'test1,test2,test3'
Requirement to strip the last occurence of ','
Just use rstrip().
result = your_string.rstrip(',')
str = 'test1,test2,test3,'
str[:-1] # 'test1,test2,test3'
The question is very old but tries to give the better answer
str = 'test1,test2,test3,'
It will check the last character, if the last character is a comma it will remove otherwise will return the original string.
result = str[:-1] if str[-1]==',' else str
Though it is little bit over work for something like that. I think this statement will help you.
str = 'test1,test2,test3,'
result = ','.join([s for s in str.split(',') if s]) # 'test1,test2,test3'
If you have to remove the last comma (also as the last character?) you can do this via the function removesuffix()
Here is an example:
>>>'hello,'.removesuffix(',')
'hello'
Actually we have to consider the worst case also.
The worst case is,
str= 'test1,test2,test3, ,,,, '
for above code, please use following code,
result = ','.join([s.strip() for s in str.split(',') if s.strip()!=''])
It will work/remove the prefix 'comma' also. For example,
str= ' , ,test1,test2,test3, ,,,, '

splitting merged words in python

I am working with a text where all "\n"s have been deleted (which merges two words into one, like "I like bananasAnd this is a new line.And another one.") What I would like to do now is tell Python to look for combinations of a small letter followed by capital letter/punctuation followed by capital letter and insert a whitespace.
I thought this would be easy with reg. expressions, but it is not - I couldnt find an "insert" function or anything, and the string commands seem not to be helpful either. How do I do this?
Any help would be greatly appreciated, I am despairing over here...
Thanks, patrick
Try the following:
re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", your_string)
For example:
import re
lines = "I like bananasAnd this is a new line.And another one."
print re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", lines)
# I like bananas And this is a new line. And another one.
If you want to insert a newline instead of a space, change the replacement to r"\1\n\2".
Using re.sub you should be able to make a pattern that grabs a lowercase and uppercase letter and substitutes them for the same two letters, but with a space in between:
import re
re.sub(r'([a-z][.?]?)([A-Z])', '\\1\n\\2', mystring)
You're looking for the sub function. See http://docs.python.org/library/re.html for documentation.
Hmm, interesting. You can use regular expressions to replace text with the sub() function:
>>> import re
>>> string = 'fooBar'
>>> re.sub(r'([a-z][.!?]*)([A-Z])', r'\1 \2', string)
'foo Bar'
If you really don't have any caps except at the beginning of a sentence, it will probably be easiest to just loop through the string.
>>> import string
>>> s = "a word endsA new sentence"
>>> lastend = 0
>>> sentences = list()
>>> for i in range(0, len(s)):
... if s[i] in string.uppercase:
... sentences.append(s[lastend:i])
... lastend = i
>>> sentences.append(s[lastend:])
>>> print sentences
['a word ends', 'A new sentence']
Here's another approach, which avoids regular expressions and does not use any imported libraries, just built-ins...
s = "I like bananasAnd this is a new line.And another one."
with_whitespace = ''
last_was_upper = True
for c in s:
if c.isupper():
if not last_was_upper:
with_whitespace += ' '
last_was_upper = True
else:
last_was_upper = False
with_whitespace += c
print with_whitespace
Yields:
I like bananas And this is a new line. And another one.

Python behavior of string in loop

In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.
s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s
print s
stdout:
These-Three_words
These-three_Words
These-three_Words
capitalize turns the first character uppercase and the rest of the string lowercase.
In the first iteration, it looks like this:
>>> [i.capitalize() for i in s.split('-')]
['These', 'Three_words']
In the second iteration, the strings are the separated into:
>>> [i for i in s.split('_')]
['These-Three', 'words']
So running capitalize on both will then turn the T in Three lowercase.
You could use title():
>>> s = 'these-three_words'
>>> print s.title()
These-Three_Words
str.capitalize capitalizes the first character and lowercases the remaining characters.
Capitalize() will return a copy of the string with only its first character capitalized. You could use this:
def cap(s):
return s[0].upper() + s[1:]

Categories

Resources