We have to define a function that will accept string argument and print it. Here, we will learn how to pass string value to the function?
我们必须定义一个接受字符串参数并打印的函数。 在这里,我们将学习如何将字符串值传递给函数 ?
Example:
例:
Input:
str = "Hello world"
Function call:
printMsg(str)
Output:
"Hello world"
Program:
程序:
# Python program to pass a string to the function
# function definition: it will accept
# a string parameter and print it
def printMsg(str):
# printing the parameter
print str
# Main code
# function calls
printMsg("Hello world!")
printMsg("Hi! I am good.")
Output
输出量
Hello world!
Hi! I am good.
Write function that will accept a string and return total number of vowels
写函数将接受字符串并返回元音总数
# function definition: it will accept
# a string parameter and return number of vowels
def countVowels(str):
count = 0
for ch in str:
if ch in "aeiouAEIOU":
count +=1
return count
# Main code
# function calls
str = "Hello world!"
print "No. of vowels are {0} in \"{1}\"".format(countVowels(str),str)
str = "Hi, I am good."
print "No. of vowels are {0} in \"{1}\"".format(countVowels(str),str)
Output
输出量
No. of vowels are 3 in "Hello world!"
No. of vowels are 5 in "Hi, I am good."
翻译自: https://www.includehelp.com/python/passing-string-value-to-the-function.aspx