Python | 带有示例的string.upper(),string.lower()和string.title()方法

string.upper(), string.lower() and string.title() Methods are inbuilt methods in Python, these are used to format string in a particular format like uppercases, lowercase or little case format.

string.upper(),string.lower()和string.title()方法是Python中的内置方法,用于将字符串格式化为特殊格式,例如大写,小写或小写。

1) string.upper()

1)string.upper()

Method returns uppercase string (where all characters of the string are in uppercase).

方法返回大写字符串(其中字符串的所有字符均为大写)。

Example: "HELLO WORLD"

示例: “ HELLO WORLD”

2) string.lower()

2)string.lower()

Method returns lowercase string (where all characters of the string are in lowercase).

方法返回小写字符串(其中字符串的所有字符均小写)。

Example: "hello world"

示例: “ hello world”

3) string.upper()

3)string.upper()

Method returns title case string (where first character of the each words are in uppercase, rest of all characters are in lowercase).

方法返回标题大小写字符串(每个单词的第一个字符为大写,其余所有字符为小写)。

Example: "Hello World"

示例: “ Hello World”

Syntaxes:

语法:

    string.upper()
    string.lower()
    string.title()

Example 1:

范例1:

# declare a string 
str = "HELLO World How are you?"

# uppercase string 
print "Uppercase string: ",str.upper()

# lowercase string
print "Lowercase string: ",str.lower()

# title case string
print "Title case string: ",str.title()

Output

输出量

    Uppercase string:  HELLO WORLD HOW ARE YOU?
    Lowercase string:  hello world how are you?
    Title case string:  Hello World How Are You?


Example 2: Change string case – if string is in uppercase, convert it to lowercase and if it is in lowercase convert it to uppercase.

示例2:更改字符串大小写–如果字符串为大写,则将其转换为小写,如果为小写,则将其转换为大写。

There is a string, we have to change its case, if string is in uppercase convert it to lowercase. If string is in lowercase convert it to uppercase, otherwise convert string into title case.

有一个字符串,我们必须更改其大小写,如果字符串是大写的,请将其转换为小写。 如果字符串为小写,则将其转换为大写,否则将其转换为标题。

# function to check and change case 
def changeCase(str) :
	
	if(str.isupper()):
		str = str.lower()
	elif(str.islower()):
		str = str.upper()
	else: 
		str = str.title()
	
	return str;

	
# Main code 
str = "HELLO WORLD"
print changeCase(str)

str = "hello world"
print changeCase(str)

str = "HELLO world"
print changeCase(str)

Output

输出量

    hello world
    HELLO WORLD
    Hello World


翻译自: https://www.includehelp.com/python/string-upper-string-lower-and-string-title-methods-with-examples.aspx

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值